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

我尝试过:

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

如何修复?


当前回答

也可以使用此方法:

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

其他回答

谁需要sed?以下是bash方式:

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

防弹解决方案。二进制数据安全,符合POSIX,但速度较慢。

POSIX已使用需要根据POSIX文本文件和POSIX线定义,因此不允许NULL字节和过长的行,并且每行必须以换行符结尾(包括最后一行)。这使得使用sed处理任意输入数据变得困难。

下面的解决方案避免了sed,而是将输入的字节转换为八进制代码,然后再转换为字节,但拦截八进制代码012(换行)并输出替换字符串来代替它。据我所知,该解决方案符合POSIX,因此它应能在多种平台上工作。

od -A n -t o1 -v | tr ' \t' '\n\n' | grep . |
  while read x; do [ "0$x" -eq 012 ] && printf '<br>\n' || printf "\\$x"; done

POSIX参考文件:sh中,shell命令语言,od中,tr中,grep,阅读[,输出函数

read、[和printf都至少在bash中内置,但POSIX可能无法保证这一点,因此在某些平台上,每个输入字节可能会启动一个或多个新进程,这会降低速度。即使在bash,这种解决方案也只能达到50kB/s左右,因此不适合大型文件。

在Ubuntu(bash、dash和busybox)、FreeBSD和OpenBSD上测试。

tr '\n' ' ' 

是命令。

简单易用。

如果您不幸不得不处理Windows行结尾,则需要删除\r和\n:

tr '\r\n' ' ' < $input > $output

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

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

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

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

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

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