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

我尝试过:

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

如何修复?


当前回答

这里是没有缓冲区的sed(适用于实时输出)。示例:在HTML中用<br/>break替换\n

echo -e "1\n2\n3" | sed 's/.*$/&<br\/>/'

其他回答

为什么我没有找到一个简单的awk解决方案?

awk '{printf $0}' file

printf将打印没有换行的每一行,如果您想用空格或其他分隔原始行:

awk '{printf $0 " "}' 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是类似的。

是sed在“正常”替换之后引入了新的行。首先,它修剪新行字符,然后根据您的指示进行处理,然后引入新行。

使用sed,您可以为每个输入行用您选择的字符串替换修剪后的行(而不是新行字符)的“结尾”;但是,sed将输出不同的行。例如,假设您希望将“行尾”替换为“==”(比用单个空格替换更通用):

PROMPT~$ cat <<EOF |sed 's/$/===/g'
first line
second line
3rd line
EOF

first line===
second line===
3rd line===
PROMPT~$

要用字符串替换新行字符,可以低效地使用tr,如前所述,用“特殊字符”替换换行字符,然后使用sed用所需的字符串替换该特殊字符。

例如:

PROMPT~$ cat <<EOF | tr '\n' $'\x01'|sed -e 's/\x01/===/g'
first line
second line
3rd line
EOF

first line===second line===3rd line===PROMPT~$

可以使用xargs:

seq 10 | xargs

or

seq 10 | xargs echo -n

在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 ~]#