Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I replace all newlines with space except the last newline. I can replace all newline to space using tr but how I can do it with some exceptions?

share|improve this question
up vote 10 down vote accepted

You can use paste -s -d ' ' file.txt:

$ cat file.txt
one line
another line
third line
fourth line

$ paste -s -d ' ' file.txt 
one line another line third line fourth line
share|improve this answer
Cool! The -s and -d options seem like made for this case. – Ketan Feb 8 '14 at 22:08
+1 My kind of guy! My favorite tool is paste! – slm Feb 8 '14 at 23:57

You can use tr to replace all newlines to space and pass the output to sed and replace the last space back to a newline:

tr '\n' ' ' < afile.txt | sed '$s/ $/\n/'
share|improve this answer

Re-implementing vonbrand's idea in Perl, provided the file is small enough:

perl -p00e 's/\n(?!\Z)/ /g' your_file
share|improve this answer

Something like sed -e 's;\n\(.\); \1;' should do...

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.