代码之家  ›  专栏  ›  技术社区  ›  Hamy

使用grep时使用引号?

  •  17
  • Hamy  · 技术社区  · 15 年前

    Grep的行为有所不同,这取决于我在regex中使用了什么样的引号。我似乎不明白为什么会这样。下面是一个问题示例:

    hamiltont$ grep -e show\(  test.txt 
      variable.show();
      variable.show(a);
      variable.show(abc, 132);
      variableshow();
    hamiltont$ grep -e "show\("  test.txt 
    grep: Unmatched ( or \(
    hamiltont$ grep -e 'show\('  test.txt 
    grep: Unmatched ( or \(
    

    我只是假设有一些合适的方法用单引号/双引号将regex括起来。有什么帮助吗?

    grep --version 退货 grep (GNU grep) 2.5.1

    4 回复  |  直到 15 年前
        1
  •  26
  •   Florian Diesch    15 年前

    包含参数的命令行在执行之前由shell处理。你可以用 要查看shell的功能:

    $ echo grep -e show\(  test.txt 
    grep -e show( test.txt
    
    $ echo grep -e "show\("  test.txt 
    grep -e show\( test.txt
    
    $ echo grep -e 'show\('  test.txt 
    grep -e show\( test.txt
    

    因此,如果没有引号,反斜杠将被删除,使“(”成为grep的普通字符(grep使用 默认情况下,使用-E使grep使用 扩展 正则表达式)。

        2
  •  4
  •   Beta    15 年前

    整齐:

    grep -e show( test.txt
    

    ( ) .

    这两种方法都有效:

    grep -e 'show(' test.txt
    grep -e "show(" test.txt
    

    因为shell将引用的文本视为文本,并将其传递给grep。

    grep -e 'show\(' test.txt
    grep -e "show\(" test.txt
    

    show\( 对格雷普来说,格雷普看到了 \( \)

        3
  •  3
  •   Scott Thomson    15 年前

    引号改变了grep的看法。非引号形式中的反斜杠(\)由shell处理,shell将反斜杠后面的字符视为特殊字符。这发生在grep获取参数之前。格雷普看到了 显示( . 当使用引号(单引号或双引号)时,shell会将其解释为“别管内容”,grep这样认为 显示\( 以及 \( 字符在grep中有意义,它正在寻找右括号-\)。

        4
  •  0
  •   W Devauld    15 年前

    我不相信这是格雷普的行为不同,这是贝壳。我假设你在用bash

    http://www.faqs.org/docs/bashman/bashref_8.html

    基本上,引用的版本在斜杠上的行为是不同的,这取决于引用机制。

    这两个引用的例子在没有斜杠的情况下都是有效的。对于第一个,shell将跳出(并传入just show)以获取模式。