How to find all files containing specific text in Linux
Abstract: in files ending with .log extension in /var/log directory and its sub-directories. grep -rlw --include="*.log" -e "tecadmin" /var/login all files in /
How to search a directory tree for all files containing specific text strings on Linux using the command line. This tutorial will help you to search all files matching a string recursively. This tutorial uses the 「grep」 command to search strings in files. Alternatively, You can also also use the find command to search files with specific string.
Syntaxgrep -rwl 「search-string」 /path/to/serch/dir1. Search Single String in All Files
The 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-201702262. 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/log3. Search String in Specific Files
You can search strings 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/log4. 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/log5. 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/logFrequently 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