使用反向引用的多行 sed [英] multiline sed using backreferences

查看:59
本文介绍了使用反向引用的多行 sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用命令行脚本转换补丁脚本 - 在这些脚本中有两行的组合,例如:

I'm converting patch scripts using a commandline script - within these scripts there's the combination two lines like:

--- /dev/null
+++ filename.txt

需要转换为:

--- filename.txt
+++ filename.txt

最初我尝试过:

less file.diff | sed -e "s/---\/dev\null\n+++ \(.*\)/--- \1\n+++ \1/"

但我不得不发现 sed 中的多行处理要复杂得多:(

But I had to find out that multiline-handling is much more complex in sed :(

感谢任何帮助...

推荐答案

您也可以先将整个文件放入保持缓冲区,然后将保持缓冲区复制到模式缓冲区并将您的正则表达式应用于整个文件(匹配换行符)用\n).

You can also first get the whole file into the holding buffer, then copy the holding buffer to the pattern buffer and apply your regexp on the whole file (matching newlines with \n).

看起来像这样:

sed -n '1h;1!H;${;g;s/a/b/g;p;}'

一些解释:

  • 1h - 如果第一行复制第一个复制到保持缓冲区
  • 1!H - 如果不是第一行,则将 (H) 附加到保持缓冲区
  • ${...} - 如果最后一行执行
  • ;g;s/a/b/g;p;- g 复制保存到模式缓冲区,s/a/b/g 做正则表达式匹配(在这种情况下用 'b' 替换 'a'),p 打印结果
  • 1h - if first line copy first copy to holding buffer
  • 1!H - if not first line append (H) to holding buffer
  • ${...} - if last line do
  • ;g;s/a/b/g;p; - g copy holding to pattern buffer, s/a/b/g do the regular expression match (in this case replace 'a' with 'b'), p print the result

这篇关于使用反向引用的多行 sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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