将除最后一个以外的所有换行符替换为空格

45 bash shell-script text-processing tr

除了最后一个换行符之外,如何用空格替换所有换行符。我可以使用将所有换行符替换为空格,tr但除了一些例外我怎么做?

gre*_*eke 51

您可以使用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
Run Code Online (Sandbox Code Playgroud)


mkc*_*mkc 12

您可以使用tr将所有换行符替换为空格并将输出传递给sed并将最后一个空格替换回换行符:

tr '\n' ' ' < afile.txt | sed '$s/ $/\n/'
Run Code Online (Sandbox Code Playgroud)


Jos*_* R. 7

在 Perl 中重新实现vonbrand 的想法,前提是文件足够小:

perl -p00e 's/\n(?!\Z)/ /g' your_file
Run Code Online (Sandbox Code Playgroud)