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

我尝试过:

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

如何修复?


当前回答

sed -i ':a;N;$!ba;s/\n/,/g' test.txt

tr "\n" <file name>

其他回答

也可以使用标准文本编辑器:

printf '%s\n' '%s/$/ /' '%j' 'w' | ed -s file

注意:这会将结果保存回文件。

与这里的大多数sed答案一样,此解决方案的缺点是必须首先将整个文件加载到内存中。

也可以使用此方法:

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:

seq 10 | xargs

or

seq 10 | xargs echo -n

另一种GNU sed方法,几乎与Zsolt Botykai的答案相同,但这使用了sed不太常用的y(音译)命令,这节省了一个字节的代码(后面的g):

sed ':a;N;$!ba;y/\n/ /'

人们可能希望y的运行速度比s快(也许以tr的速度,快20倍),但在GNU sed v4.2.2中,y比s慢4%左右。


更便携的BSD sed版本:

sed -e ':a' -e 'N;$!ba' -e 'y/\n/ /'
sed -i ':a;N;$!ba;s/\n/,/g' test.txt

tr "\n" <file name>