如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用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 ~]#
其他回答
易于理解的解决方案
我有这个问题。最重要的是,我需要在BSD(Mac OS X)和GNU(Linux和Cygwin)sed和tr上工作的解决方案:
$ echo 'foo
bar
baz
foo2
bar2
baz2' \
| tr '\n' '\000' \
| sed 's:\x00\x00.*:\n:g' \
| tr '\000' '\n'
输出:
foo
bar
baz
(后面有换行符)
它可以在Linux、OS X和BSD上运行,即使没有UTF-8支持或使用蹩脚的终端。
使用tr将换行符与另一个字符交换。NULL(\000或\x00)很好,因为它不需要UTF-8支持,也不太可能被使用。使用sed匹配NULL如果需要,使用tr交换回额外的换行符
您可以使用xargs-默认情况下,它将用空格替换\n。
但是,如果您的输入有任何未终止的引号,例如给定行上的引号符号不匹配,则会出现问题。
Perl版本以您预期的方式工作。
perl -i -p -e 's/\n//' file
正如评论中所指出的,值得注意的是,这些编辑是到位的-i.bak将在替换之前为您提供原始文件的备份,以防您的正则表达式没有您想象的那么聪明。
试试看:
echo "a,b"|sed 's/,/\r\n/'
也可以使用此方法:
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并打印确切结果。