Linux / UNIX: Sed Replace Newline

Posted on in Categories , , , , , , , , last updated November 6, 2009

How do I replace newline (\n) with sed under UNIX / Linux operating systems?

You can use the following sed command:

sed '{:q;N;s/\n//g;t q}' /path/to/data.txt

You can replace newline (\n) with * character or word ‘FOO’:

sed '{:q;N;s/\n/*/g;t q}' /path/to/data.txt

OR

sed '{:q;N;s/\n/FOO/g;t q}' /path/to/data.txt

OR replace it with tab (\t):

sed '{:q;N;s/\n/\t/g;t q}' /path/to/data.txt

To update file use -i option:

sed -i '{:q;N;s/\n/\t/g;t q}' /path/to/data.txt

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 4 comments/add one below):

4 comment

  1. Doesn’t work for me in Cygwin, if there are 17 lines the first line has 16 of the replacement, line 2 will have 15 etc until the last line does not have the replacement.

Leave a Comment