about:benjie

Random learnings and other thoughts from an unashamed geek

Using Sed to Replace Newlines

| Comments

Annoyingly, Mac OS X’s sed is not 100% compatible with GNU sed, and so this solution from StackOverflow did not immediately solve my issue:

Or use this solution with sed:
sed ':a;N;$!ba;s/\n/ /g'
This will read the whole file in a loop, then replaces the newline(s) with a space.

Update: explanation.

  1. create a register via :a
  2. append the current and next line to the register via N
  3. if we are before the last line, branch to the created register $!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 space on the pattern space (which is the contents of the a register = the whole file.

The solution I found was to split the command up into explicit separate commands:

Replacing newlines with spaces using sed on Mac OS X
1
sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g'

Comments