如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
针对上述“tr”解决方案,在Windows上(可能使用Gnuwin32版本的tr),建议的解决方案:
tr '\n' ' ' < input
对我不起作用,它可能会出错,或者出于某种原因实际上替换了\n w/“”。
使用tr的另一个功能,“delete”选项-d确实有效:
tr -d '\n' < input
或“\r\n”而不是“\n”
其他回答
@OP,如果您想替换文件中的换行符,可以只使用dos2unix(或unix2dox)
dos2unix yourfile yourfile
也可以使用此方法:
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并打印确切结果。
这真的很简单。。。当我找到解决办法时,我真的很生气。又少了一个反斜杠。这就是:
sed -i "s/\\\\\n//g" filename
tr '\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