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

我尝试过:

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

如何修复?


当前回答

可以使用xargs:

seq 10 | xargs

or

seq 10 | xargs echo -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替换换行符?

…在命令行的freebsd 7.2中不起作用:

( echo foo ; echo bar ) | sed ':a;N;$!ba;s/\n/ /g'
sed: 1: ":a;N;$!ba;s/\n/ /g": unused label 'a;N;$!ba;s/\n/ /g'
foo
bar

但如果您将sed脚本放在文件中或使用-e“构建”sed脚本。。。

> (echo foo; echo bar) | sed -e :a -e N -e '$!ba' -e 's/\n/ /g'
foo bar

> cat > x.sed << eof
:a
N
$!ba
s/\n/ /g
eof

> (echo foo; echo bar) | sed -f x.sed
foo bar

也许OS X中的sed是类似的。

使用允许查找和替换\n

sed -ie -z 's/Marker\n/# Marker Comment\nMarker\n/g' myfile.txt

标记

成为

#标记注释标记

这里是没有缓冲区的sed(适用于实时输出)。示例:在HTML中用<br/>break替换\n

echo -e "1\n2\n3" | sed 's/.*$/&<br\/>/'

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

cat test.txt |  while read line; do echo -n "$line "; done