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

我尝试过:

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

如何修复?


当前回答

在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

其他回答

用任何字符串替换换行符,并替换最后一个换行符

纯tr解决方案只能替换为单个字符,纯sed解决方案不能替换输入的最后一行。以下解决方案解决了这些问题,并且似乎对二进制数据是安全的(即使使用UTF-8语言环境):

printf '1\n2\n3\n' |
  sed 's/%/%p/g;s/@/%a/g' | tr '\n' @ | sed 's/@/<br>/g;s/%a/@/g;s/%p/%/g'

结果:

1<br>2<br>3<br>

易于理解的解决方案

我有这个问题。最重要的是,我需要在BSD(Mac OS X)和GNU(Linux和Cygwin)sed和tr上工作的解决方案:

$ echo 'foo
bar
baz


foo2
bar2
baz2' \
| tr '\n' '\000' \
| sed 's:\x00\x00.*:\n:g' \
| tr '\000' '\n'

输出:

foo
bar
baz

(后面有换行符)

它可以在Linux、OS X和BSD上运行,即使没有UTF-8支持或使用蹩脚的终端。

使用tr将换行符与另一个字符交换。NULL(\000或\x00)很好,因为它不需要UTF-8支持,也不太可能被使用。使用sed匹配NULL如果需要,使用tr交换回额外的换行符

也可以使用此方法:

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并打印确切结果。

您可以使用xargs-默认情况下,它将用空格替换\n。

但是,如果您的输入有任何未终止的引号,例如给定行上的引号符号不匹配,则会出现问题。

Perl版本以您预期的方式工作。

perl -i -p -e 's/\n//' file

正如评论中所指出的,值得注意的是,这些编辑是到位的-i.bak将在替换之前为您提供原始文件的备份,以防您的正则表达式没有您想象的那么聪明。