Grep递归和计数

Cod*_*x73 11 linux bash shell scripting

需要在文件中搜索包含大量子目录的目录:

我正在使用:

grep -c -r "string here" *
Run Code Online (Sandbox Code Playgroud)

我如何总计发现次数?

如何输出仅存档至少具有一个实例的文件?

eph*_*ent 10

使用Bash的进程替换,这给出了我认为你想要的输出?(如果不是,请澄清问题.)

grep -r "string here" * | tee >(wc -l)
Run Code Online (Sandbox Code Playgroud)

这运行grep -r正常,输出既是stdout又是wc -l进程.


Nic*_*sta 9

它适用于我(它获取每个文件中找到的'字符串'的总数).但是,它不会显示搜索的所有文件的总数.以下是如何获得它:

grep -c -r 'string' file > out && \
    awk -F : '{total += $2} END { print "Total:", total }' out
Run Code Online (Sandbox Code Playgroud)

列表将会输出,总数将发送到STDOUT.

这是Python2.5.4目录树上的输出:

grep -c -r 'import' Python-2.5.4/ > out && \
    awk -F : '{total += $2} END { print "Total:", total }' out
Total: 11500

$ head out
Python-2.5.4/Python/import.c:155
Python-2.5.4/Python/thread.o:0
Python-2.5.4/Python/pyarena.c:0
Python-2.5.4/Python/getargs.c:0
Python-2.5.4/Python/thread_solaris.h:0
Python-2.5.4/Python/dup2.c:0
Python-2.5.4/Python/getplatform.c:0
Python-2.5.4/Python/frozenmain.c:0
Python-2.5.4/Python/pyfpe.c:0
Python-2.5.4/Python/getmtime.c:0
Run Code Online (Sandbox Code Playgroud)

如果您只想获得出现'string'的行,请更改为:

grep -c -r 'import' Python-2.5.4/ | \
    awk -F : '{total += $2; print $1, $2} END { print "Total:", total }'
Run Code Online (Sandbox Code Playgroud)

这将输出:

[... snipped]
Python-2.5.4/Lib/dis.py 4
Python-2.5.4/Lib/mhlib.py 10
Python-2.5.4/Lib/decimal.py 8
Python-2.5.4/Lib/new.py 6
Python-2.5.4/Lib/stringold.py 3
Total: 11500
Run Code Online (Sandbox Code Playgroud)

您可以更改文件($ 1)和每个文件的计数($ 2)的打印方式.