Beamtic's logo
  1. Create user
Home

Share via:

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.

27 views

Edited: 2020-07-28 15:26

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.

Comments

  1. About the problem with using sudo with graphical programs in Linux.
  2. This simple tutorial shows how to solve the problem with duplicated icons created by custom .desktop files.
  3. My experience with do-release-upgrade is that it rarely breaks anything, so I would say it is generally a safe and reliable way to upgrade Ubuntu.
  4. How to use 7zip to make and extract archives from terminal.

More in: Linux Tutorials