Добавить перенос строки linux

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. 

Источник

как добавить перенос строки

Подскажите, как в bash в конец текствого файла добавить перенос на новую строку?

Re: как добавить перенос строки

Ты уже утомил дурными вопросами. Это просто неуважение к форуму.

Re: как добавить перенос строки

Солидарен с sdio. Попробуй хотя бы книжку какую-нибудь почитать.

Re: как добавить перенос строки

Вот нада все подобные вопросы закинуть в FAQ, и потом кричать: В FAQ с****ы дети (с)LOR

Читайте также:  Послать сообщение пользователю linux

Re: как добавить перенос строки

Закидывай, к lor-wiki у тебя доступ есть.

Re: как добавить перенос строки

😀
В голову пришло:
for i in `cat 1`; do echo «$i» >> 2; done; echo «» >> 2; mv 2 1

Re: как добавить перенос строки

ну ессно 1 это у нас файл в котором нужно добавить пуструю строку в конец

Re: как добавить перенос строки

что-то у тебя как-то сложно или я задачу не правильно понял мне по описанию задачи в голову пришло только echo -e «\n» >> file

Re: как добавить перенос строки

=)
Да че первое в голову пришло то и написал

Re: как добавить перенос строки

Re: как добавить перенос строки

-en, а то два переноса добавишь

Re: как добавить перенос строки

Re: как добавить перенос строки

Ну что ж вы преднамеренно товарищу усложняете задачу? Еще оставите самое плохое впечатление от unix/linux и человек навсегда свернет с истинного пути. Доставит человече нужных утилит и задача решается совершенно тривиально: ps aux | grep $$ | tail -1 | uuencode -m - | head -1 | gzip -cf | bzip2 -c | hexdump | tr ' ' '\n' | sort | uniq | grep -E '^$ >> file.txt И все. Видите, как легко. Уверен - пример не идеален, его еще можно и нужно оптимизировать, для того чтобы подняться до уровня тантризма командной строки и наконец-то постичь богов восточного склона Цзи-Чжу в bash.

Источник

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:

Читайте также:  D link dwa 137 linux driver

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.

Источник

Команда echo в Linux

Команда echo — это очень простая и в то же время часто используемая встроенная команда оболочки Bash. Она имеет только одно назначение — выводить строку текста в терминал, но применяется очень часто в различных скриптах, программах, и даже для редактирования конфигурационных файлов.

В этой статье мы рассмотрим что представляет из себя команда echo linux, как ее можно использовать и в каких ситуациях. Но сначала рассмотрим синтаксис самой команды.

Читайте также:  Grep and cat in linux

Команда echo linux

Команда echo — это не системная утилита, у нее нет исполняемого файла. Она существует только внутри интерпретатора Bash. Синтаксис команды echo linux очень прост:

$ echo опции строка

Опций всего несколько, давайте рассмотрим их, чтобы вы могли лучше ориентироваться в работе утилиты:

  • -n — не выводить перевод строки;
  • -e — включить поддержку вывода Escape последовательностей;
  • -E — отключить интерпретацию Escape последовательностей.

Это все опции, если включена опция -e, то вы можете использовать такие Escape последовательности для вставки специальных символов:

  • /c — удалить перевод строки;
  • /t — горизонтальная табуляция;
  • /v — вертикальная табуляция;
  • /b — удалить предыдущий символ;
  • /n — перевод строки;
  • /r — символ возврата каретки в начало строки.

Пожалуй, это все, что нужно знать о команде echo, а теперь давайте рассмотрим как с ней работать.

Примеры работы echo

Давайте рассмотрим как пользоваться echo. Сначала просто выведем строку на экран:

echo Linux Open Source Software Technologies

Также можно вывести значение переменной. Сначала объявим переменную:

Затем выведем ее значение:

Как уже говорилось, с помощью опции -e можно включить интерпретацию специальных последовательностей. Последовательность \b позволяет удалить предыдущий символ. Например, удалим все пробелы из строки:

echo -e «Linux \bopen \bsource \bsoftware \btechnologies»

Последовательность \n переводит курсор на новую строку:

echo -e «Linux \nopen \nsource \nsoftware \ntechnologies»

С помощью \t вы можете добавить горизонтальные табуляции:

echo -e «Linux \topen \tsource \tsoftware \ttechnologies»

Можно совместить переводы строки и табуляции:

echo -e «Linux \tnopen \tnsource \tnsoftware \tntechnologies»

Точно так же можно применить вертикальную табуляцию:

echo -e «Linux \vopen \vsource \vsoftware \vtechnologies»

С помощью последовательности \r можно удалить все символы до начала строки:

echo -e «Linux \ropen source software technologies»

Последовательность -c позволяет убрать перевод на новую строку в конце сообщения:

echo -e «Linux open source software technologies\c»

Дальше — больше. Вы можете разукрасить вывод echo с помощью последовательностей управления цветом Bash. Для доступны такие цвета текста:

Например. раскрасим нашу надпись в разные цвета:

echo -e «\033[35mLinux \033[34mopen \033[32msource \033[33msoftware \033[31mtechnologies\033[0m»

С основными параметрами команды echo разобрались, теперь рассмотрим еще некоторые специальные символы bash. Вы можете вывести содержимое текущей папки просто подставив символ *:

Также можно вывести файлы определенного расширения:

Я уже говорил, что echo можно использовать для редактирования конфигурационных файлов. Вы можете использовать запись echo в файл linux, если он пуст:

echo 1 > /proc/sys/net/ipv4/ip_forward

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

echo «UUID=09ec0871-2f55-4dd5-aeb2-cacc4a67907c /var/tmp btrfs subvol=@/var/tmp 0 0» >> /etc/fstab

Если строка содержит какие-либо специальные символы или может быть понята интерпретатором неоднозначно, следует заключить ее в кавычки.

Выводы

В этой статье была рассмотрена команда echo linux. Несмотря на свою простоту, она может применяться для решения различных задач и незаменима при написании простых скриптов. Надеюсь, эта информация была вам полезной.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector