【问题标题】:sed multiline skip lines with N option带有 N 选项的 sed 多行跳过行
【发布时间】:2014-11-05 00:12:16
【问题描述】:

我对三个字符串使用带有 N 选项的 SED,但他错过了最后一个字符串。 如果行数为偶数,则一切正常

示例文本:

this is the first line   
this is the second line
this is the third line

sed 'N;s/^.*\(first.*\)\n\(second.*$\)/\1\2/;s/ //g'

我想得到

这是第一行这是第二行
第三条线

但我明白了

这是第一行这是第二行
第三行

最后一行没有被处理, sed 跳过这个下标

s/ //g

四行没问题

this is the first line   
this is the second line
this is the third line
this is the fourth line

thisisthefirstline**thisisthesecondline**
thisisthethirdline
thisisthefourthline

对于奇数行并不总是处理最后一行

一个简单的解决方案 - 使用管道

sed 'N;s/^.*\(first.*\)\n\(second.*$\)/\1\2/' | sed 's/ //g'     

但我会在没有管道的情况下这样做

【问题讨论】:

    标签: bash sed multiline


    【解决方案1】:

    因为 sed 在最后看到它不能为你 N 所以它不处理它,只需在最后一行不加 N 就可以了:

    sed '$!N;s/^.*\(first.*\)\n\(second.*$\)/\1\2/;s/ //g'

    $ 表示最后一行,!表示不是 - 所以 $!N 表示 N 除了最后一行。

    我还假设你想要 N 个问题的答案,但实际上你不需要 N 来做你正在做的事情,这样做就足够了:

    sed 's/^.*\(first.*\)\n\(second.*$\)/\1\2/;s/ //g'

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2011-10-15
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      相关资源
      最近更新 更多