Search File System for String of Text
How to search a directory and subdirectories for a given string of text in Linux with the grep command.
By. Jacob
Edited: 2023-09-26 13:08
If there is a string of text that we can not find, grep will allow us to search the file system and locate the files where the string occurs. Ideally, we should at least specify a base directory to search, rather than searching the entire partition.
For example, to search through the /etc/ directory, enter the following in the terminal:
grep -rnw '/etc/' -e "smtp.example.com"
This will search for the string smtp.example.com, in the /etc/ directory.
-r makes the search recursive, meaning that sub-directories will also be searched.
-n will include the line number in the output.
-w only include whole word matches.
-e search for a pattern.
Searching files for a string of text
Sometimes it may be useful to know where exactly a given string of text is located. For example, when configuring various services on a Linux system, it is quite easy to loose track of where specific settings can be changed — especially since different distributions may store it in different places; however, if we know the value or the name of the setting, we may simply search the file system to find which files contain the text piece we are looking for.
Some services may supplement their own settings with system settings; this is the case for Postfix, where we both need to define the server name in /etc/mailname and /etc/main.cf
If we can tell from mail headers in outgoing e-mails that the server is using the wrong name, and we can not find where this setting is located, we could simply perform a file system search for the text string that is given in the mail headers. I.e.:
grep -rnw '/etc/' -e "smtp.example.com"
Doing this should return a list of files and the exact line number where the text string has been found, allowing us to easily edit these files and change it to the correct value.
Tell us what you think: