How do I find all files containing specific text on Linux?

How do I find all files containing specific text on Linux?

Hey Mehta,

To search for a pattern in files recursively, use the grep command with the -R or -r option for recursive search. The -n option adds line numbers, and -w ensures a whole-word match. Adding -l will only display the file names of matching files.

For example, to search for the pattern “pattern” in files under ‘/path/to/somewhere/’, you can use:

grep -Rnw ‘/path/to/somewhere/’ -e ‘pattern’

You can further refine your search using --exclude, --include, and --exclude-dir flags. For instance, to search only in files with .c or .h extensions, use:

grep --include=*.{c,h} -rnw ‘/path/to/somewhere/’ -e “pattern”

To exclude files ending with .o extension, you can use:

grep --exclude=*.o -rnw ‘/path/to/somewhere/’ -e “pattern”

For excluding directories like dir1/, dir2/, and those ending with .dst/, you can use:

grep --exclude-dir={dir1,dir2,*.dst} -rnw ‘/path/to/search/’ -e “pattern”

These options provide efficient and targeted searching, similar to what you’re aiming to achieve.

Hello Mehta_tvara,

Here is the answer to the question:-

Use the find command with xargs and grep :

find /path/to/search/ -type f -print0 | xargs -0 grep -l “pattern”

This command finds all files under /path/to/search/ and passes them to grep to search for the pattern. The -l flag tells grep to only list the names of files with matching lines.

Hello Mehta,

Use the find command with xargs and grep :

find /path/to/search/ -type f -print0 | xargs -0 grep -l “pattern”

This command finds all files under /path/to/search/ and passes them to grep to search for the pattern. The -l flag tells grep to only list the names of files with matching lines.