Sed linux перенос строки

Содержание
  1. How can I replace each newline (\n) with a space using sed?
  2. 43 Answers 43
  3. Fast answer
  4. Alternatives
  5. Long answer from the sed FAQ 5.10
  6. Sed linux перенос строки
  7. 🐧 Как заменить новую строку (\n) на пробел с помощью sed?
  8. Шаг 1: Проверим содержимое файла
  9. Шаг 2: Заменим символы новой строки с помощью команды sed
  10. Шаг 3: Проверьте, что символы были заменены
  11. Заключение
  12. You may also like
  13. 📜 Чтение файла построчно на Bash
  14. 📧 В чем разница между IMAP и POP3
  15. ✔️ Как управлять контейнерами LXD от имени обычного.
  16. 📜 Руководство для начинающих по созданию первого пакета.
  17. Феноменальная популярность электроники Xiaomi: основные причины
  18. 📜 Получение вчерашней даты в Bash: Практическое руководство
  19. Использование специальных гелей при мышечных болях
  20. 📦 Как расширить/увеличить файловую систему VxFS на Linux
  21. Услуги по размещению серверного оборудования в ЦОД
  22. Для чего выполняется ИТ консалтинг на предприятиях?
  23. Leave a Comment Cancel Reply
  24. • Свежие записи
  25. • Категории
  26. • Теги
  27. • itsecforu.ru
  28. • Страны посетителей
  29. IT is good

How can I replace each newline (\n) with a space using sed?

How can I replace a newline (» \n «) with a space (» «) using the sed command? I unsuccessfully tried:

sed 's#\n# #g' file sed 's#^$# #g' file 

tr is only the right tool for the job if replace a single character for a single character, while the example above shows replace newline with a space.. So in the above example, tr could work.. But would be limiting later on.

tr in the right tool for the job because the questioner wanted to replace each newline with a space, as shown in his example. The replacement of newlines is uniquely arcane for sed but easily done by tr . This is a common question. Performing regex replacements is not done by tr but by sed , which would be the right tool. for a different question.

«tr» can also just delete the newline ` tr -d ‘\n’ ` however you may also like to delete returns to be more universal ` tr -d ‘\012\015’ `.

WARNING: «tr» acts differently with regards to a character ranges between Linux and older Solaris machines (EG sol5.8). EG: ` tr -d ‘a-z’ ` and ` tr -d ‘[a-z]’ `. For that I recommend you use «sed» which doesn’t have that difference.

@MikeS Thanks for the answer. Follow tr ‘\012’ ‘ ‘ with an echo . Otherwise the last linefeed in the file is deleted, too. tr ‘\012’ ‘ ‘ < filename; echo does the trick.

43 Answers 43

sed is intended to be used on line-based input. Although it can do what you need.

A better option here is to use the tr command as follows:

or remove the newline characters entirely:

or if you have the GNU version (with its long options)

sed works on a «stream» of input, but it comprehends it in newline delimited chunks. It is a unix tool, which means it does one thing very well. The one thing is «work on a file line-wise». Making it do something else will be hard, and risks being buggy. The moral of the story is: choose the right tool. A great many of your questions seem to take the form «How can I make this tool do something it was never meant to do?» Those questions are interesting, but if they come up in the course of solving a real problem, you’re probably doing it wrong.

tr only works with one character strings. You can’t replace all new lines with a string that is multiple characters long.

Use this solution with GNU sed :

Читайте также:  Linux show folder tree

This will read the whole file in a loop ( ‘:a;N;$!ba ), then replaces the newline(s) with a space ( s/\n/ /g ). Additional substitutions can be simply appended if needed.

  1. sed starts by reading the first line excluding the newline into the pattern space.
  2. Create a label via :a .
  3. Append a newline and next line to the pattern space via N .
  4. If we are before the last line, branch to the created label $!ba ( $! means not to do it on the last line. This is necessary to avoid executing N again, which would terminate the script if there is no more input!).
  5. Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).

Here is cross-platform compatible syntax which works with BSD and OS X’s sed (as per @Benjie comment):

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' file 

As you can see, using sed for this otherwise simple problem is problematic. For a simpler and adequate solution see this answer.

You can run this cross-platform (i.e. on Mac OS X) by separately executing the commands rather than separating with semi-colons: sed -e ‘:a’ -e ‘N’ -e ‘$!ba’ -e ‘s/\n/ /g’

See number 3 above. It seems that $! means not to do it on the last line as there should be one final newline.

This is an impressive answer. I also find it ironic that Linux tools are supposed to be «do one thing well» when it seems like most Linux tools do many things, poorly

echo «Hello\nWorld» | sed -e ‘:a’ -e ‘N’ -e ‘$!ba’ -e ‘s/\n/ /g’ returns «Hello World», but echo «Hello World» | sed -e ‘:a’ -e ‘N’ -e ‘$!ba’ -e ‘s/\n/ /g’ returns an empty string for me. I’m on MacOS Big Sur.

Fast answer

sed will loop through step 1 to 3 until it reach the last line, getting all lines fit in the pattern space where sed will substitute all \n characters

Alternatives

All alternatives, unlike sed will not need to reach the last line to begin the process

with bash, slow

while read line; do printf "%s" "$line "; done < file 

with perl, sed-like speed

with tr, faster than sed, can replace by one character only

with paste, tr-like speed, can replace by one character only

with awk, tr-like speed

Other alternative like "echo $( < file)"is slow, works only on small files and needs to process the whole file to begin the process.

Long answer from the sed FAQ 5.10

5.10. Why can't I match or delete a newline using the \n escape
sequence? Why can't I match 2 or more lines using \n?

The \n will never match the newline at the end-of-line because the
newline is always stripped off before the line is placed into the
pattern space. To get 2 or more lines into the pattern space, use
the 'N' command or something similar (such as 'H;. ;g;').

Sed works like this: sed reads one line at a time, chops off the
terminating newline, puts what is left into the pattern space where
the sed script can address or change it, and when the pattern space
is printed, appends a newline to stdout (or to a file). If the
pattern space is entirely or partially deleted with 'd' or 'D', the
newline is not added in such cases. Thus, scripts like

 sed 's/\n//' file # to delete newlines from each line sed 's/\n/foo\n/' file # to add a word to the end of each line 

will NEVER work, because the trailing newline is removed before
the line is put into the pattern space. To perform the above tasks,
use one of these scripts instead:

Читайте также:  Ldap directory server linux

Since versions of sed other than GNU sed have limits to the size of
the pattern buffer, the Unix 'tr' utility is to be preferred here.
If the last line of the file contains a newline, GNU sed will add
that newline to the output but delete all others, whereas tr will
delete all newlines.

To match a block of two or more lines, there are 3 basic choices:
(1) use the 'N' command to add the Next line to the pattern space;
(2) use the 'H' command at least twice to append the current line
to the Hold space, and then retrieve the lines from the hold space
with x, g, or G; or (3) use address ranges (see section 3.3, above)
to match lines between two specified addresses.

Choices (1) and (2) will put an \n into the pattern space, where it
can be addressed as desired ('s/ABC\nXYZ/alphabet/g'). One example
of using 'N' to delete a block of lines appears in section 4.13
("How do I delete a block of specific consecutive lines?"). This
example can be modified by changing the delete command to something
else, like 'p' (print), 'i' (insert), 'c' (change), 'a' (append),
or 's' (substitute).

Choice (3) will not put an \n into the pattern space, but it does
match a block of consecutive lines, so it may be that you don't
even need the \n to find what you're looking for. Since GNU sed
version 3.02.80 now supports this syntax:

 sed '/start/,+4d' # to delete "start" plus the next 4 lines, 

in addition to the traditional '/from here/,/to there/<. >' range
addresses, it may be possible to avoid the use of \n entirely.

Источник

Sed linux перенос строки

Здравствуйте!
Подскажите, пожалуйста, как sed'ом разбить строку на абзацы.
скажем заменить все сиволы ' на перевод строки.
Спасибо.

>Здравствуйте!
>Подскажите, пожалуйста, как sed'ом разбить строку на абзацы.
>скажем заменить все сиволы ' на перевод строки.
>Спасибо.

cat file | tr "\'" "\n"

>Здравствуйте!
>Подскажите, пожалуйста, как sed'ом разбить строку на абзацы.
>скажем заменить все сиволы ' на перевод строки.
>Спасибо.

$ echo "hjkhjk'huhjkhjk'hjkhjkhjk'jkljkl" | sed "s/'/\n/g"
hjkhjk
huhjkhjk
hjkhjkhjk
jkljkl

>Здравствуйте!
>Подскажите, пожалуйста, как sed'ом разбить строку на абзацы.
>скажем заменить все сиволы ' на перевод строки.
>Спасибо.

или так
$ echo "sdf2sfd2sd2" | sed -e 's/2/\n/g'
sdf
sfd
sd
$ uname -a
Linux L0n3R4ng3r 2.6.18 #6 Fri Nov 30 16:23:24 EET 2007 i686 Intel(R) Celeron(TM) CPU 1300MHz GenuineIntel GNU/Linux

просто это под солярку не катит:(

>echo "sdf2sfd2sd2" | sed -e 's/2/\n/g'

sdfnsfdnsdn
>uname -a

SunOS 5.9 Generic_118558-17 sun4u sparc SUNW,Sun-Fire-V490

>[оверквотинг удален]
>Celeron(TM) CPU 1300MHz GenuineIntel GNU/Linux
>
>просто это под солярку не катит:(
>
> >echo "sdf2sfd2sd2" | sed -e 's/2/\n/g'
>
>sdfnsfdnsdn
> >uname -a
>
>SunOS 5.9 Generic_118558-17 sun4u sparc SUNW,Sun-Fire-V490

Вариант с tr супер, блин забываешь истинные unix-овые команды.
На FreeBSD sed \n не понимает ( заменяет его соответственно на n

>На FreeBSD sed \n не понимает ( заменяет его соответственно на n
>

Вот поэтому и считается хорошим тоном сообщать, какая ОС используется. 😉

[. ]
> $ echo "sdf2sfd2sd2" | sed -e 's/2/\n/g'

[. ]
>просто это под солярку не катит:(

[. ]

В таком случае нужно экранировать символ новой строки:

echo "sdf2sfd2sd2" | sed -e 's/2/\
/g'

Т.е. в первой строке команды после обратного слэша нужно тут же нажать Enter и продолжить вводить команду дальше, на следующей строчке.

Высказать мнение | Ответить | Правка | Наверх | Cообщить модератору

Читайте также:  Linux can shut down

Архив | Удалить

Индекс форумов | Темы | Пред. тема | След. тема
Оцените тред (1=ужас, 5=супер)? [ Рекомендовать для помещения в FAQ]

Источник

🐧 Как заменить новую строку (\n) на пробел с помощью sed?

Если у вас есть текстовый файл с символами новой строки (\n) и вам нужно заменить их на пробелы, вы можете использовать команду sed в Linux.

В этой статье мы рассмотрим, как использовать sed для замены символов новой строки на пробелы.

Шаг 1: Проверим содержимое файла

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

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

Например, если у вас есть файл с именем “file.txt”, вы можете использовать следующую команду для отображения содержимого файла:

Шаг 2: Заменим символы новой строки с помощью команды sed

Убедившись, что вы хотите заменить символы новой строки на пробелы, вы можете использовать команду sed для этого.

Чтобы заменить символы новой строки на пробелы в файле “file.txt”, вы можете использовать следующую команду:

Эта команда выводит вывод на экран с заменой символа новой строки (\n) на символ пробела ” “.

Для замены изменений в том же файле используйте опцию -i (inline) с той же командой.

Приведенная выше команда заменит все вхождения символов новой строки на пробелы в одном и том же файле.

Шаг 3: Проверьте, что символы были заменены

После того, как вы использовали sed для замены символов новой строки на пробелы в файле, вы можете проверить, что символы были заменены, снова используя команду cat:

Эта команда выведет на экран содержимое измененного файла.

Если символы новой строки были успешно заменены на пробелы, файл должен отображаться без видимых разрывов строк.

Заключение

В этой статье мы рассмотрели, как заменить символы новой строки на пробелы в текстовом файле с помощью команды sed в Linux.

Используя команду sed с соответствующим синтаксисом, вы можете быстро и легко изменять текстовые файлы из командной строки.

Не забудьте проверить содержимое файла перед заменой символов, чтобы случайно не изменить неправильные символы.

itisgood
🐧 Примеры команд size на Linux
🐧 Что означает -z на Bash

You may also like

📜 Чтение файла построчно на Bash

📧 В чем разница между IMAP и POP3

✔️ Как управлять контейнерами LXD от имени обычного.

📜 Руководство для начинающих по созданию первого пакета.

Феноменальная популярность электроники Xiaomi: основные причины

📜 Получение вчерашней даты в Bash: Практическое руководство

Использование специальных гелей при мышечных болях

📦 Как расширить/увеличить файловую систему VxFS на Linux

Услуги по размещению серверного оборудования в ЦОД

Для чего выполняется ИТ консалтинг на предприятиях?

Leave a Comment Cancel Reply

• Свежие записи

• Категории

• Теги

• itsecforu.ru

• Страны посетителей

IT is good

В мире компьютерных игр Steam, платформа разработанная компанией Valve, является одной из самых популярных и широко используемых. Она предоставляет огромный выбор игр для…

В этой статье вы узнаете, как удалить удаленный Git-репозиторий. Процесс прост, но его полезно запомнить, чтобы избежать неожиданностей в будущем. Git – это…

В 11-й версии своей операционной системы Microsoft серьезно переработала интерфейс и убрала несколько привычных функций. Нововведения не всем пришлись по душе. Мы дадим…

Продажа ноутбука нередко становится хлопотным занятием. Кроме поиска покупателя, продавцу необходимо подготовить устройство перед проведением сделки. Но если последовательно выполнить все шаги, ничего…

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

Источник

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