How to search for a string in multiple files with grep
Find all occurrences of a text string across multiple files and directories using grep's recursive search.
Find every occurrence of a text pattern across multiple files in a directory tree using grep's
-rrecursive flag with optional filename and extension filters.
Step-by-Step: Search Multiple Files with grep
1. Search All Files in a Directory Recursively
grep -r "error" /var/log/The grep
-r flag searches every file in
/var/log/ and all subdirectories. grep prints each matching line prefixed with the filename.
2. Limit Search to Specific File Extensions
grep -r --include="*.conf" "listen" /etc/nginx/The
--include flag restricts grep to files matching the glob pattern. This searches only
.conf files within the Nginx configuration directory.
3. Show Line Numbers and Filenames
grep -rn "404" /var/log/nginx/The
-n flag adds line numbers to grep's output. Combined with
-r, each result shows
filename:line_number:matching_line.
4. List Only Filenames with Matches
grep -rl "TODO" /home/user/project/The
-l flag tells grep to print only the filenames that contain matches, without showing the matching lines.
Common Issues
grep searches binary files and outputs garbled text— Add
--binary-files=without-match or
-I to skip binary files. See
grep: Binary file matches.