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

如何使用grep查找包含一个模式但没有第二个模式的所有文件?

  •  5
  • Herms  · 技术社区  · 16 年前

    有没有一种简单的方法可以使用grep(或与其他标准命令行工具结合)来获取包含一个模式但没有第二个模式的所有文件的列表?

    在我的特定情况下,我需要包含模式的所有文件的列表:

    override.*commitProperties
    

    但不要包含:

    super.commitProperties
    

    我在Windows上,但大量使用Cygwin。我知道如何查找具有第一个模式的所有文件或不具有第二个模式的所有模式,但我不知道如何组合这些查询。

    我更喜欢通用的答案,因为我觉得很多其他人会发现这种类型的查询很有用。对于我来说,获取一个通用的解决方案并插入我的值已经足够容易了。我只是包含了我的具体实例,以便于解释。

    6 回复  |  直到 11 年前
        1
  •  10
  •   Douglas Leeder    16 年前
    grep -rl "override.*commitProperties" . | xargs grep -L "super.commitProperties"
    

    -l 打印匹配的文件

    -L 打印不匹配的文件

        2
  •  4
  •   hlovdal    16 年前

    尝试

    find . -print0 | xargs -0 grep -l "override.*commitProperties" \
    | tr '\012' '\000' | xargs -0 grep -L super.commitProperties
    

    这个 tr 命令将换行符转换为ASCII空值,以便您可以使用 -0 在第二个xargs中,避免文件名中的空格等所有问题。

    测试结果:

    /tmp/test>more 1 2 3 | cat
    ::::::::::::::
    1
    ::::::::::::::
    override.*commitProperties
    super.commitProperties
    ::::::::::::::
    2
    ::::::::::::::
    override.*commitProperties
    ::::::::::::::
    3
    ::::::::::::::
    hello world
    /tmp/test>find . -print0 | xargs -0 grep -l "override.*commitProperties" | tr '\012' '\000' | xargs -0 grep -L super.commitProperties
    ./2
    /tmp/test>
    

    如Douglas所述,find+xargs可以替换为 grep -r .

        3
  •  2
  •   DVK    16 年前

    使用两个greps和一个comm的组合,如下所示(模式是a和b)。请注意,管道grep不起作用,因为模式可能位于不同的行上。

    $ cat a
    A
    $ cat b
    B
    $ cat ab
    A
    B
    
    $ grep -l A * > A.only
    $ grep -l B * > B.only  
    
    $ comm -23 A.only B.only 
    a
    

    注意:comm命令打印两个文件共用或唯一的行。“-23“打印第一个文件独有的行,从而抑制第二个文件中的文件名。

        4
  •  2
  •   Hai Vu    16 年前

    我的解决方案与Douglas Leeder的类似,只是我不使用xargs:

    grep -l 'override.*commitProperties' $(grep -L super.commitProperties *.txt)
    

    这个 GRIP-L 命令产品不包含模式的文件列表 高级专员 , the GRIP-L 命令查找*覆盖。 佣金属性 从名单上划掉模式。

    总的来说,这是给猫剥皮的另一种方式。

        5
  •  1
  •   Matt Clarkson    16 年前

    ack -l --make "override.*commitProperties" | xargs ack -L "super.commitProperties"

    我使用了这个线程并尝试进行递归查找。花了25分钟以上才发现 ack 相反。在5分钟内完成。

    手提工具 ACK .

        6
  •  0
  •   thepace    11 年前
        grep "override.*commitProperties" *| grep -v "super.commitProperties" | cut -d":" -f1