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

使用grep或awk查找在不同行上同时包含“a”和“b”的文件

  •  2
  • andrewj  · 技术社区  · 14 年前

    有没有办法使用 grep awk

    4 回复  |  直到 14 年前
        1
  •  5
  •   Kaleb Pederson    14 年前

    这里有一个简单的例子 awk 解决方案:

    awk 'BEGIN {acnt=0; bcnt=0;} /a/ {acnt++;} /b/ {bcnt++} END { if (acnt > 0 && bcnt > 0) print "Matches"; }' $FILE
    

    一个稍微简单一点的方法就是 grep

    grep -l a $FILE && grep -l b $FILE && echo "Both a and b found in $FILE"
    

    您可能希望重定向标准输出,但上面的内容应该简单且功能强大。如果需要,可以将其包装成一个循环:

    files=""
    for x in *; do
        grep -l a $x && grep -l b $x && files="$files $x" # assuming no spaces
    done
    # now you can iterate over $files
    
        2
  •  2
  •   ghostdog74    14 年前
    awk '/a/{f=1}/b/{g=1}END{if(f && g) print "matches"}' file
    
        3
  •  0
  •   crazyscot    14 年前

    你也许可以用一些讨厌的shell来拼凑一些东西,这些shell解析grepping的输出来表示“a”,并用它来建立一个文件列表来表示“b”,但是如果是我,我会编写一个简短的perl脚本。

        4
  •  0
  •   Dennis Williamson    14 年前

    看看这是否适合你:

    grep -lP '(?m)(a.*(.*\n)*.*b)|(b.*(.*\n)*.*a)' *