[英]sed - replace several consecutive lines matching pattern
我正在嘗試用文本替換文件中的兩個連續行。 例如:
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
我知道它失敗了,因為替換是逐行進行的。 但是我該怎么辦呢?
sed '/end$/N;//s/end/finish/g' testfile.rb
結果
class Test
def procedure
nil
finish
finish
end
情況下查看它們,因此僅當第一行以end
時才在第二行中讀取 finish
代替end
perl -i -0777 -pe 's/\bend\s*\n\s*end$/finish\nfinish/ms' testfile.rb
此代碼段適用於多行模式。 sed
默認為一行。
其他方式:
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:]]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.