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

我尝试过:

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

如何修复?


当前回答

在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 '1h;1!H;$!d
     x;s/\n/ /g' YourFile

这不适用于巨大的文件(缓冲区限制),但如果有足够的内存来保存文件,则非常有效。(更正H->1h;在@hilojack的好话之后1!H)

另一个在读取时更改新行的版本(更多的cpu,更少的内存)

 sed ':loop
 $! N
 s/\n/ /
 t loop' 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替换换行符?

…在命令行的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是类似的。

使用Awk:

awk "BEGIN { o=\"\" }  { o=o \" \" \$0 }  END { print o; }"

也可以使用标准文本编辑器:

printf '%s\n' '%s/$/ /' '%j' 'w' | ed -s file

注意:这会将结果保存回文件。

与这里的大多数sed答案一样,此解决方案的缺点是必须首先将整个文件加载到内存中。