带有 sed 的正则表达式,跨多行搜索 [英] Regex with sed, search across multiple lines

查看:100
本文介绍了带有 sed 的正则表达式,跨多行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接几行,对它们执行正则表达式匹配并打印它们.我试图用 sed 做到这一点.

I'd like to concatenate a few lines, perform a regex match on them and print them. I tried to do that with sed.

也就是说,我使用了:

cat add | sed -rn '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/s/SOME_REGEX/&/p'

它仅打印与 SOME_REGEX 匹配的行,而我希望它连接 FIRST_LINE 和 LAST_LINE 之间范围内的行,并在匹配 SOME_REGEX 时打印连接.

It prints only the lines that match SOME_REGEX while I expect it to concatenate the lines from the range between FIRST_LINE and LAST_LINE and print the concatenation if it matches SOME_REGEX.

推荐答案

当使用 '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/' 时,每一行仍然是单独处理的,要连接行你需要使用保持空格或 N 命令将下一行附加到模式空间.这是一种选择:

When using '/FIRST_LINE_REGEX/,/LAST_LINE_REGEX/' each line is still processed separately, to concatenate lines you need to use the hold space or the N command to append the next line to the pattern space. Here is one option:

cat add | sed -rn '/FIRST_LINE_REGEX/{:a;N;/LAST_LINE_REGEX/{/SOME_REGEX/p;d};ba}'

评论版本:

cat add | sed -rn '/FIRST_LINE_REGEX/ {  # if line matches /FIRST_LINE_REGEX/
  :a                                       # create label a
  N                                        # read next line into pattern space
  /LAST_LINE_REGEX/ {                      # if line matches /LAST_LINE_REGEX/
    /SOME_REGEX/p                            # print if line matches /SOME_REGEX/
    d                                        # return to start
  }
  ba                                       # return to label a
}'

这篇关于带有 sed 的正则表达式,跨多行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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