首页 > 解决方案 > 链接 grep 命令以在文件中搜索与另一个模式匹配的模式

问题描述

如何链接多个 grep 命令?

例如,如果我想递归搜索所有可公开访问的 PHP 文件,即包含$_user_location = 'public; 并在所有这些文件中搜索"SendQueue(),我该怎么办?

我的几次失败尝试:

grep -rnw ./* -e "^.*user_location.*public" *.php | grep -i "^.*SendQueue().*" --color
grep -rnw ./* -e "^.*user_location.*public" *.php | xargs -0 -i "^.*SendQueue().*" --color

标签: bashgrep

解决方案


使用文件名打印 grep 结果,提取文件名并将这些文件名传递给第二个 grep。

grep -H ..... | cut -d: -f1 | xargs -d'\n' grep ....

只要文件名中没有:文件名就可以工作,通常没有文件名。

你总是可以做一个简单的旧循环:

for i in *.php; do
    if grep -q .... "$i"; then
        grep .... "$i"
    fi
done

推荐阅读