【问题标题】:How to replace a pattern with newline (\n) with sed under UNIX / Linux operating systems?如何在 UNIX/Linux 操作系统下用 sed 替换换行符 (\n) 的模式?
【发布时间】:2014-07-19 09:17:02
【问题描述】:

我有一个 txt 文件,其中包含:

Some random
text here. This file
has multiple lines. Should be one line.

我用:

sed '{:q;N;s/\n/:sl:/g;t q}' file1.txt > singleline.txt

然后得到:

Some random:sl:text here. This file:sl:has multiple lines. Should be one line.

现在我想用newline (\n) 字符替换:sl: 模式。当我使用时:

sed 's/:sl:/&\n/g' singleline.txt

我明白了:

Some random:sl:
text here. This file:sl:
has multiple lines. Should be one line.

如何用换行符替换模式而不是在模式后添加换行符?

【问题讨论】:

  • :sl: 模式是什么意思?
  • sed 's/:sl:/\n/g' singleline.txt
  • @AvinashRaj :sl: 表示“单行”。也可以是其他任何东西。

标签: unix text replace sed newline


【解决方案1】:

Sed 使用& 作为匹配模式的快捷方式。所以你用:s1:\n替换:s1:

像这样改变你的 sed 命令:

sed 's/:sl:/\n/g' singleline.txt

【讨论】:

  • 仅供参考,这不适用于sed 的macOS(可能还有BSD?)版本;来自手册页:“但是,您不能在地址或替换命令中使用文字换行符。”如果您期望这种行为,可能需要使用 MacPorts 或 Homebrew(通常以 gsed 提供)安装 GNU sed。
【解决方案2】:

您可以使用 tr 更轻松地做到这一点:tr '\n' ' ' < singleline.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2015-03-18
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2012-11-28
    • 2022-12-05
    相关资源
    最近更新 更多