Linux / UNIX: Sed Replace Newline (\n) character

In sed, the newline character can be replaced with the \n escape sequence. To replace newlines in a file, use the following command:

sed ':a;N;$!ba;s/\n/ /g' inputfile > outputfile

This command reads the entire input file into the pattern space, replaces newlines with spaces, and writes the result to the output file.

Alternatively, to replace a newline with a different string, such as a comma, use the following command:

sed ':a;N;$!ba;s/\n/,/g' inputfile > outputfile

This command replaces newlines with commas. The :a;N;$!ba command sequence reads the entire input file into the pattern space, and the s/\n/,/g command replaces newlines with commas.

Leave a Comment