Linux знак переноса строки

Перевод строки

Перевод строки, или разрыв строки — продолжение печати текста с новой строки, то есть с левого края на строку ниже, или уже на следующей странице.

Терминология

Возврат каретки (англ. carriage return, CR) — управляющий символ ASCII (0x0D, 1310, ‘\r’), при выводе которого курсор перемещается к левому краю поля, не переходя на другую строку. Этот управляющий символ вводится клавишей «Enter». Будучи записан в файле, в отдельности рассматривается как перевод строки только в системах Macintosh.

Подача строки (от англ. line feed, LF — «подача [бумаги] на строку») — управляющий символ ASCII (0x0A, 10 в десятичной системе счисления, ‘\n’), при выводе которого курсор перемещается на следующую строку. В случае принтера это означает сдвиг бумаги вверх, в случае дисплея — сдвиг курсора вниз, если ещё осталось место, и прокрутку текста вверх, если курсор находился на нижней строке. Возвращается ли при этом курсор к левому краю или нет, зависит от реализации.

Способы представления

Способ представления перевода строки в текстовом файле часто зависит от используемой операционной системы:

LF ( ASCII 0x0A) используется в Multics, UNIX, UNIX-подобных операционных системах (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD и др.), BeOS, Amiga UNIX, RISC OS и других;

CR ( ASCII 0x0D) используется в 8-битовых машинах Commodore, машинах TRS-80, Apple II, системах Mac OS до версии 9 и OS -9;

CR+LF ( ASCII 0x0D 0x0A) используется в DEC RT-11 и большинстве других ранних не-UNIX- и не-IBM-систем, а также в CP/M, MP/M (англ.), MS -DOS, OS /2, Microsoft Windows, Symbian OS , протоколах Интернет.

Конвертирование

Способы конвертирования файла:

Файл → Сохранить как… → Конец строки → …

tr -d '\r' dos.file >unix.file tr -d '\015' dos.file >unix.file sed --in-place 's/$/\r/' unix2dos.file sed --in-place 's/\x0d$//' dos2unix.file

Источник

How to Echo Newline in Bash

In Bash, there are multiple ways we can display a text in the console or terminal. We can use either the echo or printf command to print a text. Each of these commands has their unique behaviors.

In this guide, we’ll learn how to print a newline in Bash.

Newline in Bash

Before going further, here’s a quick refresh on what a newline is. It’s usually used to specify the end of a line and to jump to the next line. It’s expressed with the character “\n” in UNIX/Linux systems. Most text editors will not show it by default.

Printing Newline in Bash

There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine.

Using the backslash character for newline “\n” is the conventional way. However, it’s also possible to denote newlines using the “$” sign.

Printing Newline Using Echo

The echo command takes a string as input and prints it out on the console screen. To print any text, we use the echo command in the following manner:

As mentioned earlier, the newline character is “\n”, right? How about we try to include it directly with echo?

Well, that didn’t go as expected. What happened?

By default, the echo command will print the string provided, character by character. It doesn’t interpret backslash characters. However, we can fix this by adding the flag “-e”. It enables backslash character interpretation. Let’s fix the command and run it again:

Voila! Now it’s working as expected!

This technique also works when using Bash variables. Take a look at the following example:

$ sentence = «The \n Quick \n Brown \n Fox»

Printing Newline Using $

We can also use the “$” sign with the echo command to specify the newline character. This method is a bit more complex than the previous one. The explanation is best done with an example.

Run the following command:

  • The given string isn’t inside double quotations.
  • Before each newline character “\n”, we’re using the “$” sign.
  • Each newline character “\n” is provided inside single quote.

Printing Newlines with Multiple Echo Statements

In this approach, we’re basically going to run multiple echo commands instead of one. By default, echo prints the given string and adds a newline character at the end. By running multiple echo statements at once, we’re taking advantage of that.

Let’s have a look at the following example.

  • We’re running 4 echo commands.
  • Each command is separated by a semicolon (;). It’s the default delimiter in Bash.

Printing Newline with Printf

Similar to echo, the printf command also takes a string and prints it on the console screen. It can be used as an alternative to the echo command.

Have a look at the following example.

As you can see, printf processes backslash characters by default, no need to add any additional flags. However, it doesn’t add an additional newline character at the end of the output, so we have to manually add one.

Final Thoughts

In this guide, we’ve successfully demonstrated how to print newlines in Bash. The newline character is denoted as “\n”. Using both the echo and printf commands, we can print strings with new lines in them. We can also cheat (well, technically) by running the same tool multiple times to get the desired result.

For more in-depth info about echo and printf, refer to their respective man pages.

Interested in Bash programming? Bash is a powerful scripting language that can perform wonders. Check out our Bash programming section. New to Bash programming? Get started with this simple and comprehensive guide on Bash scripting tutorials for beginners.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

How to add new lines when using echo

I didn’t know about printf, with printf it works 😛 . so what does it make not working with echo then?

There are many different implementations of echo command incompatible with each other. Thus it is recommended to use more standard tool as printf . See unix.stackexchange.com/questions/65803/… for extended overview of the problem.

9 Answers 9

Pass the -e flag to echo to make it parse escaped characters such as «\r\n», like so:

echo -e "Line 1\r\nLine2" >> readme.txt 

A nice simple «-e» option to get escape sequences working — it says on another answer that echo is unreliable and doesn’t follow standards unlike printf .

echo

An echo implementation which strictly conforms to the Single Unix Specification will add newlines if you do:

But that is not a reliable behavior. In fact, there really isn’t any standard behavior which you can expect of echo .

OPERANDS

string

A string to be written to standard output. If the first operand is -n , or if any of the operands contain a character, the results are implementation-defined.

On XSI-conformant systems, if the first operand is -n , it shall be treated as a string, not an option. The following character sequences shall be recognized on XSI-conformant systems within any of the arguments:

\a — Write an .

\b — Write a .

\c — Suppress the that otherwise follows the final argument in the output. All characters following the \c in the arguments shall be ignored.

\f — Write a .

\n — Write a .

\r — Write a .

\t — Write a .

\v — Write a .

\\ — Write a character.

\0num — Write an 8-bit value that is the zero, one, two, or three-digit octal number num .

And so there really isn’t any general way to know how to write a newline with echo , except that you can generally rely on just doing echo to do so.

A bash shell typically does not conform to the specification, and handles the -n and other options, but even that is uncertain. You can do:

shopt -s xpg_echo echo hey\\nthere 

And not even that is necessary if bash has been built with the build-time option.

—enable-xpg-echo-default

Make the echo builtin expand backslash-escaped characters by default, without requiring the -e option. This sets the default value of the xpg_echo shell option to on , which makes the Bash echo behave more like the version specified in the Single Unix Specification, version 3. See Bash Builtins, for a description of the escape sequences that echo recognizes.

printf

On the other hand, printf ‘s behavior is pretty tame in comparison.

RATIONALE

The printf utility was added to provide functionality that has historically been provided by echo . However, due to irreconcilable differences in the various versions of echo extant, the version has few special features, leaving those to this new printf utility, which is based on one in the Ninth Edition system.

The EXTENDED DESCRIPTION section almost exactly matches the printf() function in the ISO C standard, although it is described in terms of the file format notation in XBD File Format Notation.

It handles format strings which describe its arguments — which can be any number of things, but for strings are pretty much either %b yte strings or literal %s trings. Other than the %f ormats in the first argument, it behaves most like a %b yte string argument, except that it doesn’t handle the \c escape.

echo() printf

You might write your own standards conformant echo like.

. which should pretty much always do the right thing automatically.

Actually, no. That prints a literal \n at the tail of the arguments if the last argument ends in an odd number of .

echo() case $ in (\ *) printf %b\\n "$*";; (*) IFS=\ $IFS printf %b\\n "$*" IFS=$ esac 

Источник

How can I have a newline in a string in sh?

What should I do to have a newline in a string? Note: This question is not about echo. I’m aware of echo -e , but I’m looking for a solution that allows passing a string (which includes a newline) as an argument to other commands that do not have a similar option to interpret \n ‘s as newlines.

13 Answers 13

If you’re using Bash, you can use backslash-escapes inside of a specially-quoted $’string’ . For example, adding \n :

STR=$'Hello\nWorld' echo "$STR" # quotes are required here! 

If you’re using pretty much any other shell, just insert the newline as-is in the string:

Bash recognizes a number of other backslash escape sequences in the $» string. Here is an excerpt from the Bash manual page:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \" double quote \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \cx a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. 

Источник

Читайте также:  Linux монитор сетевой активности
Оцените статью
Adblock
detector