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

我尝试过:

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

如何修复?


当前回答

@OP,如果您想替换文件中的换行符,可以只使用dos2unix(或unix2dox)

dos2unix yourfile yourfile

其他回答

以下内容比大多数答案简单得多。此外,它还在发挥作用:

echo `sed -e 's/$/\ |\ /g' file`

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

cat test.txt |  while read line; do echo -n "$line "; done
sed -i ':a;N;$!ba;s/\n/,/g' test.txt

tr "\n" <file name>

还有一种选择:

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

其中tr-s表示:

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

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

如果您不幸不得不处理Windows行结尾,则需要删除\r和\n:

tr '\r\n' ' ' < $input > $output