在linux命令行中使用find和grep来搜索具有特定用户和文本内容的文件?

Sam*_*Sam 3 linux bash shell

我试图找到属于特定用户的文件,该文件还包含特定的文本字符串.例如,我想找到一个属于root用户的文件,并包含"hello there"文本.

我知道我可以使用grep搜索文件中的文本,例如:

grep -irl "hello there" /directory1
Run Code Online (Sandbox Code Playgroud)

而且,我知道我可以搜索具有特定扩展名的用户拥有的文件:

find -user root -name "*.txt"
Run Code Online (Sandbox Code Playgroud)

有没有办法可以将这两个命令结合起来?

Joh*_*ica 5

grep使用所有匹配文件调用一次:

find -user root -name "*.txt" -exec grep -il "hello there" {} +
Run Code Online (Sandbox Code Playgroud)

或者grep -q为每个文件和-print匹配的文件调用一次.

find -user root -name "*.txt" -exec grep -iq "hello there" {} \; -print
Run Code Online (Sandbox Code Playgroud)

(-exec可以像-user或者一样用作测试-name.如果命令成功,则-exec测试通过并被-print调用.)