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

我尝试过:

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

如何修复?


当前回答

@OP,如果您想替换文件中的换行符,可以只使用dos2unix(或unix2dox)

dos2unix yourfile yourfile

其他回答

答案是:标签。。。

如何使用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是类似的。

在某些情况下,您可以将RS更改为其他字符串或字符。这样,\n可用于sub/gsub:

$ gawk 'BEGIN {RS="dn" } {gsub("\n"," ") ;print $0 }' file

shell脚本的强大之处在于,如果您不知道如何以一种方式执行,您可以用另一种方式来执行。很多时候,你要考虑的事情比简单问题的复杂解决方案要多。

关于呆呆的事情。。。并将文件读入内存,我不知道这一点,但对我来说,gawk似乎一次只能使用一行,而且速度非常快(没有其他一些快,但编写和测试的时间也很重要)。

我处理MB甚至GB的数据,我发现的唯一限制是行大小。

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

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

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

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

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

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

在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

也可以使用此方法:

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并打印确切结果。