This tutorial will teach you how to recursively search for files containing a specific string on Linux using the command line. This tutorial uses the ‘grep’ command to search for strings in files. Alternatively, you may use the find command to look for files with specific content.
A basic syntax for searching text with grep command:
The grep command offers other useful options for finding specific text in file systems.
-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 a pattern to search or specify multiple search strings
-w, --word-regexp: force to match whole words
There are several ways to use the grep command to search text. Let’s discuss a few examples of searching a text/string in the file system.
- Search Single String in All Files
The below example command will search the string “Error” in all files in /var/log directory and its sub-directories.
grep -rlw "Error" /var/log
- Search Multiple String in All Files
-eswitch can also be utilized to find multiple strings. This is comparable to the
egrepprogram. The example below will look for “Error” and “Warning” in all the files in the /var/log directory and its subdirectories.
grep -rlw -e "Error" -e "Warning" /var/log
- Search String in Specific Files
You can search strings in files that match the file name criteria. The following command searches for “Error” in files with the .log extension in the /var/log directory and its sub-directories.
grep -rlw --include="*.log" -e "Error" /var/log
- Exclude Some Files from Search
You can use the
--excludeoption in find to exclude some files that match certain file name criteria. For example, you can exclude files with the .txt extension.
grep -rlw --exclude="*.txt" -e "tecadmin" /var/log
- Exclude Some Directories from Search
You can also skip searching certain directories. For instance, don’t search for string files in any folder with apache2 in its name.
grep -rlw --exclude-dir="*apache2*" -e "tecadmin" /var/log
You have learned how to search for specific text in files on the Linux file system in this tutorial.
Another useful command switch is “-s”
This suppresses errors where files are not readable, or there are permission errors, etc.
very helpful & clear: Many thanks!
Good job! really helpful.
Really helpful. Good Job
Well laid out. Thank you.
Thanks, very helpful…