【问题标题】:Querying selective files using grep使用 grep 查询选择性文件
【发布时间】:2013-10-20 18:47:14
【问题描述】:

我有 10 个文件夹,名称分别为 1 到 10。每个文件夹下都有多个文件。我想在选择性文件夹中寻找模式,例如在名为 2 到 6 的文件夹中包含的文件中。如何在 shell 上实现这一点?我知道有一种方法可以在 shell 脚本中使用 for 循环,如下所述:

for ((i=2;i<=6;i++)); do grep 'pattern' $i/*; done

但在这种情况下,它将触发 5 个不同的 grep 命令,我需要在最后进行整理。

是否有直接的正则表达式语法来完成此操作?

【问题讨论】:

    标签: regex linux shell unix grep


    【解决方案1】:

    如果我正确理解了您的问题,您可以像这样进行大括号扩展:

    grep 'pattern' {2..6}/*
    

    【讨论】:

    • 或者,只要简单,字符类:grep foo [2-6]/*
    • @Berei,Kevin - 谢谢!
    【解决方案2】:

    您可以使用-r 选项和--exclude-dir 选项。

    -r, --recursive
    Read all files under each directory, recursively, following symbolic links only 
    if they are on the command line.  This is equivalent to the -d recurse option.
    
    
    --exclude-dir=DIR
    Exclude directories matching the pattern DIR from recursive searches.
    

    演示

    ls
    f1 f2  f3  f4  f5  f6  f7  f8  f9 f10
    

    每个文件夹都包含一个文件file,其中包含字符串abc

    $ grep --exclude-dir 'f[1,7-9]' --exclude-dir 'f10' -r 'abc'       
    f5/file:abc
    f4/file:abc
    f2/file:abc
    f3/file:abc
    f6/file:abc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2021-01-31
      • 2018-04-12
      • 2013-09-30
      • 1970-01-01
      相关资源
      最近更新 更多