【问题标题】:sed replaces string by line break but not the other way around [duplicate]sed 通过换行符替换字符串,但不是相反[重复]
【发布时间】:2014-06-21 20:12:48
【问题描述】:

我正在尝试替换换行符,我想要为此使用sed(请不要建议替代工具)。用我正在尝试的字符串替换换行符

sed 's/\n/string/g'

工作,至少在我的系统上(Ubuntu 12.04 上的 bash)。但是以下

sed 's/string/\n/g'

确实用换行符替换所有出现的string

例如,考虑以下file

hello
there

sed 's/\n/ /g' file 给了我同样的结果:

hello
there

但是sed 's/hello/hello\n/g' file 给了我一个换行符:

hello

there

有人能告诉我为什么sed 能够写入 \n 的新行但不能读取吗?

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    sed 适用于输入行,您不能像那样替换换行符。您需要将 输入行 附加到模式空间。

    sed ':a;$!N;s/\n/string/;ta' inputfile
    

    将用string 替换换行符。

    【讨论】:

    • 这就是为什么我会使用不同的工具:-)
    【解决方案2】:
     sed -n '1h;1!H;$x;s/\n/string/gp' YourFile
    

    其他方法,首先加载到缓冲区中,最后一次性更改并打印结果

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 2019-10-14
      • 2012-03-08
      • 2020-03-13
      • 1970-01-01
      • 2014-09-17
      • 2016-09-22
      • 2023-03-20
      • 2021-06-21
      相关资源
      最近更新 更多