Find Files that Contains Specific Text in Linux

When working with files in Linux, there may need to find all files that contains a specific text. This tutorial shows how to do that.

The grep command can be used for searching files containing specific text. For example, the following command find all files under the /etc directory recursively that contains localhost text:

sudo grep -rwn "localhost" /etc

Output example:

/etc/lvm/lvm.conf:1210: #     System IDs beginning localhost are not permitted.
/etc/hosts:1:127.0.0.1 localhost
/etc/hosts:5:::1     ip6-localhost ip6-loopback

Used options:

  • r - enables recursive files searching. It means to find all files in the specified directory and all subdirectories. Instead of -r, use the -R option if want to follow all symbolic links.
  • w - specifies that particular text should match the whole word.
  • n - shows numbers of the lines that contains particular text.

Use -l option instead of -n, to show only filenames that contains particular text:

sudo grep -rwl "localhost" /etc

Output example:

/etc/lvm/lvm.conf
/etc/hosts

Leave a Comment

Your email address will not be published.