如何使用 sed 替换换行符 ( )? [英] How can I replace a newline ( ) using sed?
问题描述
如何使用 sed
命令将换行符(
")替换为空格(")?>
我尝试失败:
sed 's#
# #g' 文件sed 's#^$# #g' 文件
我该如何解决?
将此解决方案与 GNU sed
一起使用:
sed ':a;N;$!ba;s/
//g' 文件
这将循环读取整个文件 (':a;N;$!ba
),然后用空格替换换行符 (s/
//g
).如果需要,可以简单地附加其他替换.
说明:
sed
首先将不包括换行符的第一行读入模式空间.- 通过
:a
创建标签. - 通过
N
在模式空间中添加换行符和下一行. - 如果我们在最后一行之前,分支到创建的标签
$!ba
($!
表示不要在最后一行做.这是必须的避免再次执行N
,如果没有更多输入,这将终止脚本!) - 最后,替换将每个换行符替换为模式空间(即整个文件)上的一个空格.
这里是跨平台兼容的语法,它适用于 BSD 和 OS X 的 sed
(根据 @Benjie 评论):
sed -e ':a' -e 'N' -e '$!ba' -e 's/
//g' 文件
如您所见,使用 sed
解决这个原本很简单的问题是有问题的.有关更简单和适当的解决方案,请参阅此答案.
How can I replace a newline ("
") with a space ("") using the
sed
command?
I unsuccessfully tried:
sed 's#
# #g' file
sed 's#^$# #g' file
How do I fix it?
Use this solution with GNU sed
:
sed ':a;N;$!ba;s/
/ /g' file
This will read the whole file in a loop (':a;N;$!ba
), then replaces the newline(s) with a space (s/
/ /g
). Additional substitutions can be simply appended if needed.
Explanation:
sed
starts by reading the first line excluding the newline into the pattern space.- Create a label via
:a
. - Append a newline and next line to the pattern space via
N
. - If we are before the last line, branch to the created label
$!ba
($!
means not to do it on the last line. This is necessary to avoid executingN
again, which would terminate the script if there is no more input!). - Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).
Here is cross-platform compatible syntax which works with BSD and OS X's sed
(as per @Benjie comment):
sed -e ':a' -e 'N' -e '$!ba' -e 's/
/ /g' file
As you can see, using sed
for this otherwise simple problem is problematic. For a simpler and adequate solution see this answer.
这篇关于如何使用 sed 替换换行符 ( )?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!