【问题标题】:sed - replace several consecutive lines matching patternsed - 替换匹配模式的几个连续行
【发布时间】:2013-04-20 17:20:56
【问题描述】:

我正在尝试用我的文本替换文件中的两个连续行。例如:
testfile.rb

class Test
  def procedure
    nil
  end
end

我正在努力实现这一目标:
testfile.rb

class Test
  def procedure
    nil
  finish
finish

所以我需要替换最后两行,但这不起作用:

sed -i 's/^\s\send\nend/  finish\nfinish/' testfile.rb

我知道它失败了,因为替换是逐行进行的。但是我该怎么做呢?

【问题讨论】:

    标签: regex linux bash sed


    【解决方案1】:
    sed '/end$/N;//s/end/finish/g' testfile.rb
    

    结果

    class Test
      def procedure
        nil
      finish
    finish
    
    • 我们只想查看可能同时包含end 的一对行,所以 仅当第一行以 end 结尾时才在第二行中读取
    • end 替换为finish

    【讨论】:

    • 明白。非常感谢!您的最后一次编辑更短,但对我来说更难阅读。但也不太灵活。也许留下两个变种?
    • sed -i '/end$/{N; s/end\nend/finish\nfinish/}' testfile.rb 更适合我
    【解决方案2】:
    perl -i -0777 -pe 's/\bend\s*\n\s*end$/finish\nfinish/ms' testfile.rb
    

    这个 sn-p 在多行模式下工作。 sed 默认为一行。

    【讨论】:

    • 完美运行,但它不是 Perl 的 sed。还是谢谢。
    【解决方案3】:

    另一种方式:

    sed 'N;s/^  end\nend$/  finish\nfinish/;t;P;D' testfile.rb
    

    灵活的缩进:

    sed 'N;s/^\( *\)end\n\( *\)end$/\1finish\n\2finish/;t;P;D' testfile.rb
    

    为了更灵活的缩进,将空格更改为[[:space:]]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 2016-12-17
      • 2015-04-10
      • 2018-08-12
      • 2012-03-07
      • 2021-04-02
      相关资源
      最近更新 更多