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?
6 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
-
1
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/'
Re-implementing vonbrand's idea in Perl, provided the file is small enough:
perl -p00e 's/\n(?!\Z)/ /g' your_file
-
+1 because this method works for replacements with multibyte characters (as opposed to GNU paste)– myrddDec 21, 2018 at 16:27
This worked for me.
tr '\n' ' ' < file_with_new_line | sed 's/\ $//g' > file_with_space
-
-
-
Yes I have. Have you? Your
tr
command replaces all newlines with spaces and yoursed
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 usingg
in thesed
command. Since you're using$
, it can only match at the end, theg
is pointless. You also don't need to escape the space, the `` makes no difference either.– terdon ♦Mar 1, 2016 at 12:14
you can use this trick:
echo $(cat file.txt)
-
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 whereecho
isn't builtin. Jul 5, 2021 at 5:29