Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 

How do I fix it?

like image 320
hhh Avatar asked Aug 09 '09 19:08

hhh


People also ask

How do you replace special characters in sed?

You need to escape the special characters with a backslash \ in front of the special character. For your case, escape every special character with backslash \ .

Does sed support multiline replacement?

By default, when sed reads a line in the pattern space, it discards the terminating newline (\n) character. Nevertheless, we can handle multi-line strings by doing nested reads for every newline.


2 Answers

Use this solution with GNU sed:

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

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.

Explanation:

  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.

like image 45
Zsolt Botykai Avatar answered Oct 26 '22 19:10

Zsolt Botykai


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:

tr '\n' ' ' < input_filename 

or remove the newline characters entirely:

tr -d '\n' < input.txt > output.txt 

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

tr --delete '\n' < input.txt > output.txt 
like image 182
dmckee --- ex-moderator kitten Avatar answered Oct 26 '22 21:10

dmckee --- ex-moderator kitten