Find all files containing a specific text or pattern on Linux

· Thomas Taylor

Searching for a specific text or pattern across multiple files can be completed using grep.

Using grep to search file contents

grep provides searching functionality out-of-the-box:

1grep -rnw '/path/to/directory' -e 'pattern'

Here are a breakdown of the grep options:

The command will output the file names and text containing the pattern. If the goal is simply to display the filenames themselves, add the -l flag.:

1grep -rlnw '/path/to/directory' -e 'pattern'

If binary files need to be omitted, add the -I flag.

1grep -rlnwI '/path/to/directory' -e 'pattern'

In addition, the --exclude, --include, and --exclude-dir may be used in combination.

Example: Excluding dir1 and dir2, find all html or javascript files with the filter of p in them.

1grep \
2  --include=\*.{html,js} \
3  --exclude-dir={dir1,dir2} \
4  -rlnwI '/path/to/directory' \
5  -e "p"


Reply to this post by email ↪