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?
Asked
Active
Viewed 6.7k times
55
Gilles 'SO- stop being evil'
- 807,993
- 194
- 1,674
- 2,175
-
1`sed -z 's/\n/ /g; s/.$//'` - assuming "the last" newline is at the end of the stream (what you probably mean) – bloody Mar 31 '23 at 08:12
6 Answers
63
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
grebneke
- 4,621
- 25
- 20
-
1Cool! The `-s` and `-d` options seem like made for this case. – Ketan Maheshwari Feb 08 '14 at 22:08
18
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/'
X Tian
- 10,413
- 2
- 33
- 48
Ketan Maheshwari
- 9,054
- 6
- 40
- 53
7
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) – myrdd Dec 21 '18 at 16:27
-1
This worked for me.
tr '\n' ' ' < file_with_new_line | sed 's/\ $//g' > file_with_space
Abhijit
- 101
- 1
-
-
-
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 01 '16 at 12:14
-1
you can use this trick:
echo $(cat file.txt)
mrash
- 99
- 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. – dave_thompson_085 Jul 05 '21 at 05:29