如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
以前的大多数sed命令示例在我的Unix系统中都不适用,并给出错误消息:
Label too long: {:q;N;s/\n/ /g;t q}
这适用于所有Unix/Linux环境:
line=$(while read line; do echo -n "$line "; done < yoursourcefile.txt)
echo $line |sed 's/ //g' > sortedoutput.txt
第一行将从文件yoursourcefile.txt中删除所有新行,并生成一行。第二个sed命令将删除其中的所有空格。
其他回答
谁需要sed?以下是bash方式:
cat test.txt | while read line; do echo -n "$line "; done
易于理解的解决方案
我有这个问题。最重要的是,我需要在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交换回额外的换行符
使用允许查找和替换\n
sed -ie -z 's/Marker\n/# Marker Comment\nMarker\n/g' myfile.txt
标记
成为
#标记注释标记
答案是:标签。。。
如何使用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是类似的。
在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 ~]#