In this small series I will introduce Linux shell commands.
Search for a File containing a string in Linux
To find a file containing a certain string in a directory use grep:
grep "search_string" /directory_to_search/*
To search for a file in all subdirectories containing a certain string recursively add -r:
grep -r "search_string" /directory_to_search
To search for all occurrences of a string in a file just specify that filename:
grep "search_string" filename.txt
To only show file names add -l:
grep -r -l "search_string" /directory_to_search/
For more useful flags read the grep man pages.
Advanced grep Text Search: Logical Operators and Exclusion of Results
egrep provides more regular expression characters, so we can do a bit more:
It is possible to use the OR logical operator when searching files for text in linux.
To search for a file containing one string OR another string use:
egrep "search_string|other_string" /directory_to_search/*
To exclude egrep search results containing a string use:
egrep ""search_string|other_string"" /directory_to_search/* | egrep -v "exclude_this|and_this"
If you still want to color in the original search terms in the output you might want to add another egrep:
egrep "search_string|other_string" /directory_to_search/* | egrep -v "exclude_this|and_this" | "search_string|other_string"
I could not find a better way of doing this. But as it is only to color in the search results in the shell the performance drop of calling egrep three times should not really matter.