How to Find all files Containing Specific Text on Linux. This tutorial will help you to search all files containing specific string recursively. This tutorial uses “grep” command to search string in files. Alternatively, You can also use find command to search text.
grep -rwl “search-string” /path/to/serch/dir
1. Search Single String in All Files
Below example command will search string “tecadmin” in all files in /var/log directory and its sub-directories.
grep -rlw "tecadmin" /var/log/var/log/lfd.log /var/log/cloud-init.log /var/log/messages-20170226 /var/log/audit/audit.log.1 /var/log/btmp-20170315 /var/log/httpd/access_log-20170226
2. Search Multiple String in All Files
You can also specify multiple strings to search using -e switch. This is similar to egrep command. Below example will search strings “tecadmin” and “https” in all files in /var/log directory and its sub-directories.
$ grep -rlw -e "tecadmin" -e "https" /var/log
3. Search String in Specific Files
You can search string in files matching the file name criteria. Below example command will search string “tecadmin” in files ending with .log extension in /var/log directory and its sub-directories.
$ grep -rlw --include="*.log" -e "tecadmin" /var/log
4. Exclude Some Files from Search
If you want to exclude some files matching file name criteria. You can exclude some files using –exclude option in command. For example, do not search file ending with .txt extension.
# grep -rlw --exclude="*.txt" -e "tecadmin" /var/log
5. Exclude Some Directories from Search
You can also exclude some directoires to skip search inside it. For example, do not search string files inside any folder having http in their name.
# grep -rlw --exclude-dir="*http*" -e "tecadmin" /var/log
Frequently Uses Command Switches
Below is the frequently uses grep command switches. To list all switches details use
grep --help command.
-r, --recursive Search files recursively -R, --dereference-recursive Search files recursively and follow symlinks --include=FILE_PATTERN search only files that match FILE_PATTERN --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN --exclude-from=FILE skip files matching any file pattern from FILE --exclude-dir=PATTERN directories that match PATTERN will be skipped. -L, --files-without-match Print file names containing no match -l, --files-with-matches Print string containing file names only -i, --ignore-case ignore case of search string -e, --regexp=PATTERN Use patter to search or specify multiple search strings -w, --word-regexp force to match whole words