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

我尝试过:

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

如何修复?


当前回答

以前的大多数sed命令示例在我的Unix系统中都不适用,并给出错误消息:

Label too long: {:q;N;s/\n/ /g;t q}

这适用于所有Unix/Linux环境:

line=$(while read line; do echo -n "$line "; done < yoursourcefile.txt)
echo $line |sed 's/ //g' > sortedoutput.txt

第一行将从文件yoursourcefile.txt中删除所有新行,并生成一行。第二个sed命令将删除其中的所有空格。

其他回答

我使用了一种混合方法,通过使用tr用制表符替换换行符,然后用我想要的任何内容替换制表符,来绕过换行符的问题。在本例中,“”,因为我试图生成HTML分隔符。

echo -e "a\nb\nc\n" |tr '\n' '\t' | sed 's/\t/ <br> /g'`

也可以使用此方法:

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

sed旨在用于基于行的输入。尽管它可以满足你的需要。


这里更好的选择是使用tr命令,如下所示:

tr '\n' ' ' < input_filename

或完全删除换行符:

tr -d '\n' < input.txt > output.txt

或者如果您有GNU版本(带有长选项)

tr --delete '\n' < input.txt > output.txt

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

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