Riven Lv 3 Riven Lv 3 - 1 year ago 54
Linux Question

"find" specific contents [linux]

I would like to go through all the files in the current directory (or sub-directories) and echoes me back the name of files only if they contain certain words.

More detail:

find -type f -name "*hello *" will give me all file names that have "hello" in their names. But instead of that, I want to search through the files and if that file's content contains "hello" then prints out the name of the file.

Is there a way to approach this?

Answer Source

You can use GNU find and GNU grep as

find /path -type f -exec grep -Hi 'hello' {} +

This is efficient in a way that it doesn't invoke as many grep instances to as many files returned from find. This works in an underlying assumption that find returns a set of files for grep to search on. If you are unsure if the files may not be available, as a fool-proof way, you can use xargs with -r flag, in which case the commands following xargs are executed only if the piped commands return any results

find /path -type f | xargs -r0 grep -Hi 'hello'