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

我尝试过:

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

如何修复?


当前回答

为了使用awk将所有换行符替换为空格,而不将整个文件读入内存:

awk '{printf "%s ", $0}' inputfile

如果需要最后一行换行符:

awk '{printf "%s ", $0} END {printf "\n"}' inputfile

可以使用空格以外的字符:

awk '{printf "%s|", $0} END {printf "\n"}' inputfile

其他回答

答案是:标签。。。

如何使用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?以下是bash方式:

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

以下内容比大多数答案简单得多。此外,它还在发挥作用:

echo `sed -e 's/$/\ |\ /g' file`
sed -i ':a;N;$!ba;s/\n/,/g' test.txt

tr "\n" <file name>