Can Sed Replace New Line Characters?

sed

Is there an issue with sed and new line character?
I have a file test.txt with the following contents

aaaaa  
bbbbb  
ccccc  
ddddd  

The following does not work:
sed -r -i 's/\n/,/g' test.txt

I know that I can use tr for this but my question is why it seems not possible with sed.

If this is a side effect of processing the file line by line I would be interested in why this happens. I think grep removes new lines. Does sed do the same?

Best Answer

With GNU sed and provided POSIXLY_CORRECT is not in the environment (for single-line input):

sed -i ':a;N;$!ba;s/\n/,/g' test.txt

From https://stackoverflow.com/questions/1251999/sed-how-can-i-replace-a-newline-n :

  1. create a label via :a
  2. append the current and next line to the pattern space via N
  3. if we are before the last line, branch to the created label $!ba ($! means not to do it on the last line (as there should be one final newline)).
  4. finally the substitution replaces every newline with a comma on the pattern space (which is the whole file).