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?
5 Answers
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.
- 1Cool! The
-sand-doptions seem like made for this case.Ketan– Ketan2014-02-08 22:08:20 +00:00Commented Feb 8, 2014 at 22:08
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/' 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 because this method works for replacements with multibyte characters (as opposed to GNU paste)myrdd– myrdd2018-12-21 16:27:10 +00:00Commented Dec 21, 2018 at 16:27
you can use this trick: echo $(cat file.txt)
- 1Not 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 whereechoisn't builtin.dave_thompson_085– dave_thompson_0852021-07-05 05:29:48 +00:00Commented Jul 5, 2021 at 5:29
sed -z 's/\n/ /g; s/.$//'- assuming "the last" newline is at the end of the stream (what you probably mean)sed -z 'y/\n/ /;s/ $/\n/'. the-zdoesn't put the ending newline back in the stream, so you need to add it back in manually. (usingyhere since it acts more liketr)