42

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?

49

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
| improve this answer | |
  • 1
    Cool! The -s and -d options seem like made for this case. – mkc Feb 8 '14 at 22:08
10

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/'
| improve this answer | |
5

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

perl -p00e 's/\n(?!\Z)/ /g' your_file
| improve this answer | |
  • +1 because this method works for replacements with multibyte characters (as opposed to GNU paste) – myrdd Dec 21 '18 at 16:27
-1

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

| improve this answer | |
-1

This worked for me.

tr '\n' ' ' < file_with_new_line   | sed 's/\ $//g' > file_with_space
| improve this answer | |
  • That will remove the last newline as well. – terdon Feb 29 '16 at 8:58
  • I don't think so, it is working fine. Have you really tried it??? – Abhijit Mar 1 '16 at 11:20
  • Yes I have. Have you? Your tr command replaces all newlines with spaces and your sed command removes the last space. This results in a file without a final newline and so is not what the question is asking for. By the way, there's no point int using g in the sed command. Since you're using $, it can only match at the end, the g is pointless. You also don't need to escape the space, the `` makes no difference either. – terdon Mar 1 '16 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy