55

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?

2
  • 2
    sed -z 's/\n/ /g; s/.$//' - assuming "the last" newline is at the end of the stream (what you probably mean) Commented Mar 31, 2023 at 8:12
  • @bloody more like: sed -z 'y/\n/ /;s/ $/\n/'. the -z doesn't put the ending newline back in the stream, so you need to add it back in manually. (using y here since it acts more like tr) Commented Jul 11 at 13:18

5 Answers 5

68

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 

Note that except with the paste from busybox, that turns an empty file into one with an empty line.

1
  • 1
    Cool! The -s and -d options seem like made for this case. Commented Feb 8, 2014 at 22:08
18

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

tr '\n' ' ' < afile.txt | sed 's/ $/\n/' 
8

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

perl -0777 -pe 's/\n(?!\Z)/ /g' your_file 

Or, without having to load the whole file in memory:

perl -pe 's/\n/ / unless eof' your_file 
1
  • +1 because this method works for replacements with multibyte characters (as opposed to GNU paste) Commented Dec 21, 2018 at 16:27
-2

you can use this trick: echo $(cat file.txt)

1
  • 1
    Not if there are multiple (adjacent) spaces, or empty or all-space lines, or any word in the file contains shell 'glob' characters/constructs (* ? [..]) that match any file(s) in the current directory, or depending on your shell sometimes even if they don't match. Or if the file size exceeds approximately ARG_MAX on shells where echo isn't builtin. Commented Jul 5, 2021 at 5:29
-3

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

0

You must log in to answer this question.