如何使用grep的正则表达式

时间:2021-08-25 19:29:05

I just used the following grep command:

我刚刚使用了以下grep命令:

grep -ri '^(<topicref |<mapref).*( )(dest=")'

to match the following:

匹配以下内容:

<topicref version="1" dest="susu"/>
<mapref id="" dest="summat"/>

all topicref and mapref that have a dest attribute.

具有dest属性的所有topicref和mapref。

However, it didnt work although regexpal accepts the regex. How do I have to change this to work with grep?

但是,虽然regexpal接受正则表达式,但它没有用。如何将其更改为与grep一起使用?

1 个解决方案

#1


1  

If you would like to use parentheses and alternation without using extended regular expressions, you can escape them with the backslash to enable this functionality.

如果要在不使用扩展正则表达式的情况下使用括号和替换,可以使用反斜杠对其进行转义以启用此功能。

grep -ir '^\(<topicref \|<mapref\).*\( \)\(dest="\)' .

Or, you can use -E option, and then you do not have to escape brackets:

或者,您可以使用-E选项,然后您不必转义括号:

grep -iEr '^(<topicref |<mapref).*( )(dest=")' .

Mind the . at the end stands for the current directory, and together with r recursive option, this will fetch you all the matches in the directory files.

记住。最后代表当前目录,与r recursive选项一起,这将获取目录文件中的所有匹配项。

#1


1  

If you would like to use parentheses and alternation without using extended regular expressions, you can escape them with the backslash to enable this functionality.

如果要在不使用扩展正则表达式的情况下使用括号和替换,可以使用反斜杠对其进行转义以启用此功能。

grep -ir '^\(<topicref \|<mapref\).*\( \)\(dest="\)' .

Or, you can use -E option, and then you do not have to escape brackets:

或者,您可以使用-E选项,然后您不必转义括号:

grep -iEr '^(<topicref |<mapref).*( )(dest=")' .

Mind the . at the end stands for the current directory, and together with r recursive option, this will fetch you all the matches in the directory files.

记住。最后代表当前目录,与r recursive选项一起,这将获取目录文件中的所有匹配项。