如何使用sed命令将换行符(“\n”)替换为空格(“”)?

我尝试过:

sed 's#\n# #g' file
sed 's#^$# #g' file

如何修复?


当前回答

也可以使用此方法:

sed 'x;G;1!h;s/\n/ /g;$!d'

解释

x   - which is used to exchange the data from both space (pattern and hold).
G   - which is used to append the data from hold space to pattern space.
h   - which is used to copy the pattern space to hold space.
1!h - During first line won't copy pattern space to hold space due to \n is
      available in pattern space.
$!d - Clear the pattern space every time before getting the next line until the
      the last line.

Flow

当第一行从输入中获取时,进行交换,因此1进入保留空间,\n进入模式空间,将保留空间附加到模式空间,执行替换并删除模式空间。

在第二行中,进行交换,2到保持空间,1到模式空间,G将保持空间附加到模式空间中,h将模式复制到其中,进行替换并删除。此操作将继续,直到达到EOF并打印确切结果。

其他回答

我特别喜欢的解决方案是在保留空间中追加所有文件,并替换文件末尾的所有换行符:

$ (echo foo; echo bar) | sed -n 'H;${x;s/\n//g;p;}'
foobar

然而,有人告诉我,在一些sed实现中,保持空间可能是有限的。

为了使用awk将所有换行符替换为空格,而不将整个文件读入内存:

awk '{printf "%s ", $0}' inputfile

如果需要最后一行换行符:

awk '{printf "%s ", $0} END {printf "\n"}' inputfile

可以使用空格以外的字符:

awk '{printf "%s|", $0} END {printf "\n"}' inputfile

针对上述“tr”解决方案,在Windows上(可能使用Gnuwin32版本的tr),建议的解决方案:

tr '\n' ' ' < input

对我不起作用,它可能会出错,或者出于某种原因实际上替换了\n w/“”。

使用tr的另一个功能,“delete”选项-d确实有效:

tr -d '\n' < input

或“\r\n”而不是“\n”

在Mac OS X上(使用FreeBSD sed):

# replace each newline with a space
printf "a\nb\nc\nd\ne\nf" | sed -E -e :a -e '$!N; s/\n/ /g; ta'
printf "a\nb\nc\nd\ne\nf" | sed -E -e :a -e '$!N; s/\n/ /g' -e ta

使用Awk:

awk "BEGIN { o=\"\" }  { o=o \" \" \$0 }  END { print o; }"