bash grep 反斜杠在负面回顾中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11685038/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep backslash in negative lookbehind
提问by Simon
I want to find the number of occurrences of XXXin my latex document that are not in the form of a command as \XXX. Therefore I am looking for occurrences that are not preceded by a backslash.
我想XXX在我的乳胶文档中找到不是命令形式的\XXX. 因此,我正在寻找前面没有反斜杠的事件。
I tried the following:
我尝试了以下方法:
grep -c -e '(?<!\)XXX' test.tex    #result: grep: Unmatched ) or \)
grep -c -e '(?<!\)XXX' test.tex   #result: 0
grep -c -e "(?<!\)XXX" test.tex   #result: -bash: !\: event not found
none of them work as intended. In fact I don't understand the last error message at all.
它们都没有按预期工作。事实上,我根本不明白最后一条错误消息。
My test.tex contains only the following lines
我的 test.tex 只包含以下几行
%test.tex
XXX
\XXX
So the expected result is 1.
所以预期的结果是1。
Any ideas?
有任何想法吗?
Ps.: I am working in bash.
Ps.:我在 bash 工作。
回答by choroba
Neither standard nor extended regular expressions support the look behind. Use Perl regexes:
标准正则表达式和扩展正则表达式都不支持回看。使用 Perl 正则表达式:
grep -P '(?<!\)xxx' test.tex
回答by ?mega
Try to use
尝试使用
grep -P '(?<!\)\bXXX\b' test.tex
回答by Maxim Masiutin
If you have GNU grep, it should support Perl-compatible regular expressions with --perl-regexp or -P command-line option. The classical perl regular expression only support negated character classes, for example, [^a] means any character except "a".
如果您有 GNU grep,它应该支持带有 --perl-regexp 或 -P 命令行选项的 Perl 兼容正则表达式。经典的 perl 正则表达式只支持否定字符类,例如,[^a] 表示除“a”之外的任何字符。
The examples that you gave look like Perl-compatible regular expressions, not classical one, and you have to use GNU grep with --perl-regexp or -P command-line option or you can install PCRE-enabled grep, e.g. "pcregrep" - it doesn't need any command-line options for PCRE, and thus is more convenient.
你给出的例子看起来像 Perl 兼容的正则表达式,而不是经典的,你必须使用带有 --perl-regexp 或 -P 命令行选项的 GNU grep 或者你可以安装启用 PCRE 的 grep,例如“pcregrep” - PCRE 不需要任何命令行选项,因此更方便。
Also, you pattern doesn't look like a negative assertion. It should be
此外,你的模式看起来不像一个消极的断言。它应该是
(?!pattern)
not the
不是
(?<!pattern)
Find more here: https://perldoc.perl.org/perlre.html
在此处查找更多信息:https: //perldoc.perl.org/perlre.html
If you like perl-compatible regular expressions and have perl but don't have pcregrep or your grep doesn't support --perl-regexp, you can you one-line perl scripts that work the same way like grep. Perl accepts stdin the same way like grep, e.g.
如果您喜欢与 perl 兼容的正则表达式并且有 perl 但没有 pcregrep 或者您的 grep 不支持 --perl-regexp,您可以使用单行 perl 脚本,其工作方式与 grep 相同。Perl 像 grep 一样接受标准输入,例如
ipset list | perl -e "while (<>) {if (/packets(?! 0 )/){print;};}"

