Dealing with newlines in sed can be tricky, because of how sed naturally deals with new lines. For example, let's say you have a file or variable that contains the text "Hello World". This text will end with a new line.
Hello\n World\n How\n are\n you\n today?\n
When using sed to manipulate the file or varilable, sed will not do any sort of manipulation against the new line. For example, if you replace the word "World" with "Earth", the new line remains.
Hello\n Earth\n How\n are\n you\n today?\n
Remove new lines
In this example, new lines are replaced with a single whitespace.
- :label is a label. You could replace "label" with some other unique string of text.
- N gets the current line and the next line.
- $! means do not continue when the last line has been reached.
- b label means go to the label.
- s|\n| |g is the sed replacement command.
~]# sed ':label; N; $! b label; s|\n| |g' file.txt Hello World How are you today?