在多个文件中搜索模式的存在

时间:2018-03-15 21:16:25

标签: shell unix command-line grep

我需要确保在父目录中找到的所有文件都有特定的模式。 例如:

./a/b/status: *foo*foo
./b/c/status: bar*bar
./c/d/status: foo

该命令应返回false,因为文件2没有foo。 我正在尝试下面,但没有关于如何在单一命令中实现这一点的线索。

find . -name "status" | xargs grep -c "foo"

4 个答案:

答案 0 :(得分:1)

-c选项计算找到模式的次数。您不需要find,而是使用-r--include选项来获取grep。

$ grep -r -c foo --include=status

-r针对匹配foo的文件递归搜索patterh status

实施例。我在三个目录中有四个文件。每个都有一行;

$ cat a/1.txt b/1.txt b/2.txt c/1.txt 
foobar
bar
foo
bazfoobar

使用上面的grep,你会得到类似的东西,

$ grep -ir -c foo --include=1.txt
a/1.txt:1
b/1.txt:0
c/1.txt:1

答案 1 :(得分:1)

您可以计算不包含" foo"的文件数量,如果数字> 0表示至少有一个文件不包含" foo" :

find . -type f -name "status" | xargs grep -c "foo" | grep ':0$' | wc -l

find . -type f -name "status" | xargs grep -c "foo" | grep -c ':0$' 

或 使用iamauser回答优化(谢谢):

grep -ir -c "foo" --include=status | grep -c ':0$'

如果树中的所有文件都被命名为" status",您可以使用更简单的命令行:

grep -ir -c "foo"  | grep -c ':0$'

带支票

r=`grep -ir -c foo  | grep -c ':0$'`
if [ "$r" != "0" ]; then
   echo "false"
fi

答案 2 :(得分:0)

如果您希望find输出xargs可以读取的文件列表,则需要使用:

find . -name "status" -print0 | xargs -0 grep foo` to avoid filenames with special characters (like spaces and newlines and tabs) in them.

但我的目标是这样的:

find . -name "status" -exec grep "foo" {} \+

终止\+的{​​{1}}会导致-exec将找到的所有文件附加到find命令的单个实例上。这比为找到的每个文件运行grep一次效率要高得多,如果您使用grep,它会执行此操作。

\;的默认行为是显示文件名和匹配,如您在问题中所示。您可以使用以下选项更改此行为:

  • grep ...不显示文件名
  • -h ...仅显示匹配的文件,没有匹配的文字,
  • -l ...仅显示不匹配的文件 - 即没有模式的文件。

这最后一个听起来就像你真正想要的那样。

答案 3 :(得分:0)

find . -name 'status' -exec grep -L 'foo' {} + | awk 'NF{exit 1}'

如果所有文件都包含'foo',则上述退出状态为0,否则为1。