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

我尝试过:

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

如何修复?


当前回答

为什么我没有找到一个简单的awk解决方案?

awk '{printf $0}' file

printf将打印没有换行的每一行,如果您想用空格或其他分隔原始行:

awk '{printf $0 " "}' file

其他回答

在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

可以使用xargs:

seq 10 | xargs

or

seq 10 | xargs echo -n

试试看:

echo "a,b"|sed 's/,/\r\n/'

在sed替换部分中,键入反斜杠,按回车键转到第二行,然后以/g'结尾:

sed 's/>/\
/g'

[root@localhost ~]# echo "1st</first>2nd</second>3rd</third>" | sed 's/>/\
> /g'
1st</first
2nd</second
3rd</third

[root@localhost ~]#

这真的很简单。。。当我找到解决办法时,我真的很生气。又少了一个反斜杠。这就是:

sed -i "s/\\\\\n//g" filename