在bash中跨多行匹配正则表达式 [英] Match regex across multiple lines in bash

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

问题描述

我想匹配文件中所有以 [%开始,以%] 结尾的模式.

I want to match all patterns that start with [% and end with %] in a file.

我尝试了多种工具,例如awk,sed,pcregrep,尽管它们被建议作为类似问题的最佳答案,但它们似乎都不起作用.

I've tried multiple tools such as awk, sed, pcregrep and none of them seem to work, although they are suggested as top answers on similar questions.

[% FOREACH selection = selections -%]
      case SELECTION_ID_[% SELECTION_NAME %]: {
        const [% selectionType %]& source = this->[% selectionName %]();
        rc = bcem_AggregateUtil::toAggregate(result,
                                             d_selectionId,
                                             source);
      } break;
[% END -%]

[% foo ]

[% INCLUDE attributeSearchBlock

    tree=attributeSearchTree depth=0

    visit='ReturnAttributeInfo' name='name' nameLength='nameLength' -%]

对于上面的代码,我希望得到以下结果:

For the code above, I expect the following result:

[% FOREACH selection = selections -%]
      case SELECTION_ID_[% SELECTION_NAME %]: {
        const [% selectionType %]& source = this->[% selectionName %]();
[% END -%]
[% INCLUDE attributeSearchBlock

    tree=attributeSearchTree depth=0

    visit='ReturnAttributeInfo' name='name' nameLength='nameLength' -%]

但是我得到的是所有匹配的行.

But I am getting all the lines matched instead.

我在做什么错了?

最新编辑

如果它在多行上,也应该匹配.例如:

If it's on multiple lines, it should also be matched. For example:

[% foo
bar -%]

最新答案似乎都不起作用,因此我使用以下命令手动完成了整个过程:

LATER EDIT 2: None of the answers seems to work, so I did the whole thing manually using the following:

        hasPatternStarted=false
        while read -r line; do
            if [[ $line =~ '[%' ]]; then
                hasPatternStarted=true
            fi
            if [[ $line =~ '%]' ]]; then
                hasPatternStarted=false
                echo $line
            fi
            if [ "$hasPatternStarted" = true ]; then
                echo $line
            fi
        done < "$filename"

它工作正常,但是如果有人用一个衬板解决此问题(使用sed,awek,pcregrep,perl,grep等),请这样说.

It works fine, but if anyone has a one liner to solve this problem (using sed, awek, pcregrep, perl, grep anything), please say so.

推荐答案

如果您查看要查询的内容,则会得到两行,因为只有两个结尾为-%]

If you look at what you ask for you get two lines, since only two ends with -%]

 awk '/\[%.*-%\]/' file
[% FOREACH selection = selections -%]
[% END -%]

您可以执行以下操作以获取所有以 [%开始,以%]

You can do this to get the result with all start with [% and ends with %]

awk '/\[%.*%\]/' file
[% FOREACH selection = selections -%]
      case SELECTION_ID_[% SELECTION_NAME %]: {
        const [% selectionType %]& source = this->[% selectionName %]();
[% END -%]

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

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