Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find and grep in linux command line to search for files with a specific user and text content?

Tags:

linux

bash

shell

I am trying to find a file that belongs to a specific user, that also contains a specific string of text. For example, I want to find a file that belongs to the root user, and contains the text "hello there".

I know I can search for text in files using grep for example:

grep -irl "hello there" /directory1

And, I know I can search for files owned by a user with specific extensions:

find -user root -name "*.txt"

Is there a way that I can combine these two commands?


1 Answers

Call grep once with all of the matching files:

find -user root -name "*.txt" -exec grep -il "hello there" {} +

Or call grep -q once for each file and -print the files that match.

find -user root -name "*.txt" -exec grep -iq "hello there" {} \; -print

(-exec can be used as a test just like -user or -name. If the command succeeds, the -exec test passes and -print is invoked.)

like image 109
John Kugelman Avatar answered Jun 13 '26 17:06

John Kugelman