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

我尝试过:

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

如何修复?


当前回答

谁需要sed?以下是bash方式:

cat test.txt |  while read line; do echo -n "$line "; done

其他回答

可以使用xargs:

seq 10 | xargs

or

seq 10 | xargs echo -n

也可以使用此方法:

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

还有一种选择:

tr-s“[:space:]”“”<filename>filename2&&mv filename2文件名

其中tr-s表示:

-s、 --挤压重复替换重复字符的每个序列其列在最后指定的SET中,只出现一次该字符

这将使用单个空格替换文件中的所有空格序列,将结果写入新文件,然后将新文件重命名为原始名称。

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

这不适用于巨大的文件(缓冲区限制),但如果有足够的内存来保存文件,则非常有效。(更正H->1h;在@hilojack的好话之后1!H)

另一个在读取时更改新行的版本(更多的cpu,更少的内存)

 sed ':loop
 $! N
 s/\n/ /
 t loop' YourFile

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

tr '\n' ' ' < input

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

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

tr -d '\n' < input

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