Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(How) can I remove all newlines (\n) using sed?

Tags:

newline

sed

I tried to remove all newlines in a pipe like this:

(echo foo; echo bar) | sed -e :a -e N -e '$!ba' -e 's/\n/ /g' | hexdump -C

Which results on debian squeeze in:

00000000  66 6f 6f 20 62 61 72 0a                           |foo bar.|
00000008

Not removing the trailing newline.

tr -d '\n' as in How do I remove newlines from a text file? works just fine but isn't sed.

like image 226
j.l. Avatar asked Jul 13 '11 07:07

j.l.


People also ask

How to delete newlines from each line in a sed script?

Thus, scripts like sed 's/ //' file # to delete newlines from each line sed 's/ /foo /' file # to add a word to the end of each line the line is put into the pattern space. To perform the above tasks,

Why doesn't SED remove new lines from Foo and bar statements?

If foo and bar are not expected to contain new lines, then you must beware that will not add a new line at the end of the output. So it may be that you don't need sed to remove new lines at all even if it did remove the trailing lines.

How to replace newline in SED with NULL byte?

GNU sed supports changing the "record" separator to null byte instead of newline. tr only works with one character strings. You can't replace all new lines with a string that is multiple characters long. This will read the whole file in a loop ( ':a;N;$!ba ), then replaces the newline (s) with a space ( s/ / /g ).

How to remove “not updated” or “no available” lines from linuxhintos?

Through the sed command, we can remove the lines matching the “Not Updated” or “Not Available” pattern from the file ‘LinuxhintOS.txt’ and that command is something like this: We can remove all lines starting with any character through the sed command. We have created a new file named ‘LinuxhintOS.txt’ with the following contents:


1 Answers

Sorry can't be done using sed, please see: http://sed.sourceforge.net/sedfaq5.html#s5.10 and a discussion here: http://objectmix.com/awk/26812-sed-remove-last-new-line-2.html

Looks like sed will add back the \n if it is present as the last character.

like image 94
Kevin Burton Avatar answered Oct 15 '22 17:10

Kevin Burton