如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
这真的很简单。。。当我找到解决办法时,我真的很生气。又少了一个反斜杠。这就是:
sed -i "s/\\\\\n//g" filename
其他回答
sed -i ':a;N;$!ba;s/\n/,/g' test.txt
tr "\n" <file name>
针对上述“tr”解决方案,在Windows上(可能使用Gnuwin32版本的tr),建议的解决方案:
tr '\n' ' ' < input
对我不起作用,它可能会出错,或者出于某种原因实际上替换了\n w/“”。
使用tr的另一个功能,“delete”选项-d确实有效:
tr -d '\n' < input
或“\r\n”而不是“\n”
tr '\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并打印确切结果。
您可以使用xargs-默认情况下,它将用空格替换\n。
但是,如果您的输入有任何未终止的引号,例如给定行上的引号符号不匹配,则会出现问题。