我有一个有几行不同行的文件。我正在寻找包含(或多或少)如下模式的行:
\[.*<.*>.*\]
换句话说,我需要在[]之间有<something>
的行。例如:
Line with [ <matching>|<pattern>]
A line <that> does[not]<match>[]
But [this[<should>]be matched] too
[match [me] <buddy>]
<>之间唯一允许的字符是字母数字字符和下划线。
我尝试过上面的regexp和它的懒惰版本,但它似乎不起作用。正确的regexp是什么?
发布于 2015-08-27 05:13:32
如果您的[
、]
对总是匹配的,并且您不交叉使用[...]
s和<...>
,而您的grep
支持-P
选项(就像用PCRE支持构建的GNU grep
那样),您可以这样做:
grep -P '>(?!((?:[^]]|\[(?1)\])*)$)'
也就是说,寻找一个>
,它的后面没有匹配的[...]
对。它采用了PCREs的(?1)
递归匹配机制。
发布于 2015-08-27 05:43:42
POSIXly,您可以使用sed
:
sed '
h; # make a copy of the pristine line on the hold space
:1
/\[[^]]*<[^]]*>[^]]*]/{
# found a [...<x>...]
g; # retrieve our saved copy and branch off
b
}
s/\[\([^]]*\)]/\1/g; # remove inner [...]s
# and loop if that s command was successful
t1
# no [...] left to remove, discard this line.
d'
也就是说,删除从内部开始的[...]
对,直到在一对中找到<...>
。
(在Solaris或非常旧的系统上,删除注释,因为Solaris sed只允许行开头的注释)。
发布于 2015-08-27 04:50:21
我想出了以下解决方案:
grep -P '\[[^.\]]*<.*>[^.\[]*\]' filename
换句话说,我们在以下约束之间匹配一对<和>的和:
这个解决方案也比使用惰性量词的正则表达式快得多。
https://unix.stackexchange.com/questions/225851
复制