sed-替换多个连续的行匹配模式 [英] sed - replace several consecutive lines matching pattern

查看:86
本文介绍了sed-替换多个连续的行匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to replace two consecutive lines in a file with my text. For example:
testfile.rb

class Test
  def procedure
    nil
  end
end

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

I am trying to achieve this:
testfile.rb

class Test
  def procedure
    nil
  finish
finish

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

So I need to replace last 2 lines but this doesn't work:

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

我知道它会失败,因为替换是逐行进行的.但是我该怎么办呢?

I understand that it fails because replacement is line by line. But how can I do it?

推荐答案

sed '/end$/N;//s/end/finish/g' testfile.rb

结果

class Test
  def procedure
    nil
  finish
finish

  • 我们只想在两行都包含 end 的情况下查看它们,所以仅当第一行以 end
  • 结尾时才在第二行中读取
  • 完成
  • 替换 end

    • we want to look at a pair of lines only when they might both contain end, so only read in second line when first line ends with end
    • replace end with finish
    • 这篇关于sed-替换多个连续的行匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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