如何使用 sed 替换换行符 (\n)? [英] How can I replace a newline (\n) using sed?

查看:306
本文介绍了如何使用 sed 替换换行符 (\n)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 sed 命令用空格(")替换换行符(\n")?>

我尝试失败:

sed 's#\n# #g' 文件sed 's#^$# #g' 文件

我该如何解决?

解决方案

将此解决方案与 GNU sed 一起使用:

sed ':a;N;$!ba;s/\n//g' 文件

这将循环读取整个文件,然后用空格替换换行符.

说明:

  1. 通过 :a 创建标签.
  2. 通过 N 将当前行和下一行添加到模式空间.
  3. 如果我们在最后一行之前,分支到创建的标签 $!ba ($! 意味着不要在最后一行做,因为应该有一个最后换行).
  4. 最后,替换将每个换行符替换为模式空间(即整个文件)上的一个空格.

这是跨平台兼容的语法,适用于 BSD 和 OS X 的 sed(根据 @Benjie 评论):

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n//g' 文件

如您所见,使用 sed 解决这个原本很简单的问题是有问题的.有关更简单和适当的解决方案,请参阅此答案.

How can I replace a newline ("\n") with a space ("") using the sed command?

I unsuccessfully tried:

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

How do I fix it?

解决方案

Use this solution with GNU sed:

sed ':a;N;$!ba;s/\n/ /g' file

This will read the whole file in a loop, then replaces the newline(s) with a space.

Explanation:

  1. Create a label via :a.
  2. Append the current and next line to the pattern space via N.
  3. If we are before the last line, branch to the created label $!ba ($! means not to do it on the last line as there should be one final newline).
  4. 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/\n/ /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 替换换行符 (\n)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆