【问题标题】:Escaping a parenthesis in grep/ack在 grep/ack 中转义括号
【发布时间】:2011-06-13 06:32:22
【问题描述】:

我想查找字符串“methodname(”,但无法转义“(”。我怎样才能得到

grep methodname( *

ack-grep methodname( *

上班?

【问题讨论】:

    标签: regex grep ack


    【解决方案1】:

    解释( 有两件事:shell 和ack-grep

    您可以使用''""\( 从外壳中转义,例如

    grep 'methodname(' *
    grep "methodname(" *
    grep methodname\( *
    

    grep 默认使用基本的正则表达式语言,所以( 并不特殊。 (如果你使用 egrepgrep -Egrep -P,那就是这样。)

    另一方面,ack-grep 将 Perl 正则表达式作为输入,其中 ( 也很特殊,因此您也必须对其进行转义。

    ack-grep 'methodname\(' *
    ack-grep "methodname\\(" *
    ack-grep methodname\\\( *
    ack-grep 'methodname[(]' *
    ack-grep "methodname[(]" *
    ack-grep methodname\[\(\] *
    

    【讨论】:

    • 或者,如果您不想转义括号,对于 Perl,请使用 -Q 标志。 ack -Q 'methodname('
    • 如果你想搜索例如单引号是最好的。 PHP 变量以$ 为前缀。但话又说回来,如果你想搜索包含单引号的字符串,单引号会迫使你使用丑陋的转义:stackoverflow.com/questions/7254509/…
    • 我从来不知道 ack-grep - 谢谢!
    【解决方案2】:

    尝试在( 之前添加\

    小演示:

    $ cat file
    bar
    methodname(
    foo
    $ grep -n methodname\( file
    2:methodname(
    $ 
    

    用单引号或双引号将模式括起来也可以:

    $ grep -n 'methodname(' file
    2:methodname(
    $ grep -n "methodname(" file
    2:methodname(
    $ 
    

    【讨论】:

    • 在 grep 中工作,但不是 ack。 Ack 认为它是一个群体的一部分(我认为)
    • 问题是必须为 shell 和 ack 转义括号。
    • ack 'methodname\('ack -Q 'methodname('
    猜你喜欢
    • 2011-04-10
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多