Posted By: Anonymous
How can I replace a newline (“
n“) with a space (“
“) using the
I unsuccessfully tried:
sed 's#n# #g' file sed 's#^$# #g' file
How do I fix it?
Use this solution with GNU
sed ':a;N;$!ba;s/n/ /g' file
This will read the whole file in a loop, then replaces the newline(s) with a space.
- Create a label via
- Append the current and next line to the pattern space via
- If we are before the last line, branch to the created label
$!means not to do it on the last line as there should be one final newline).
- Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).
Here is cross-platform compatible syntax which works with BSD and OS X’s
sed (as per @Benjie comment):
sed -e ':a' -e 'N' -e '$!ba' -e 's/n/ /g' file
As you can see, using
sed for this otherwise simple problem is problematic. For a simpler and adequate solution see this answer.