如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
答案是:标签。。。
如何使用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是类似的。
其他回答
tr '\n' ' '
是命令。
简单易用。
在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
为了使用awk将所有换行符替换为空格,而不将整个文件读入内存:
awk '{printf "%s ", $0}' inputfile
如果需要最后一行换行符:
awk '{printf "%s ", $0} END {printf "\n"}' inputfile
可以使用空格以外的字符:
awk '{printf "%s|", $0} END {printf "\n"}' inputfile
还有一种选择:
tr-s“[:space:]”“”<filename>filename2&&mv filename2文件名
其中tr-s表示:
-s、 --挤压重复替换重复字符的每个序列其列在最后指定的SET中,只出现一次该字符
这将使用单个空格替换文件中的所有空格序列,将结果写入新文件,然后将新文件重命名为原始名称。
谁需要sed?以下是bash方式:
cat test.txt | while read line; do echo -n "$line "; done