Linux / UNIX: Sed Replace Newline

by on January 6, 2009 · 4 comments· last updated at 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


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 4 comments… read them below or add one }

1 jalal hajigholamali August 3, 2011 at 4:04 pm

thanks..
very nice example

Reply

2 Claudio October 28, 2011 at 9:25 pm

It doesnt work for me :(

$ sed ‘{:q;N;s/\n/\t/g;t q}’ /fi/fa/foo.fu
sed: 1: “{:q;N;s/\n/\t/g;t q}”: unexpected EOF (pending }’s)

Reply

3 Harry Phillips March 27, 2013 at 5:12 am

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.

Reply

4 Harry Phillips March 27, 2013 at 5:17 am

Simpler way to replace the end of the line:

sed ‘s/$/FOO/’ /path/to/data.txt

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , ,

Previous Faq:

Next Faq: