How to Use grep to List All Files Containing Specific String


Often you may want to use the grep command in Bash to list all files in a particular directory that contain a specific string within the file contents.

You can use the following syntax to do so:

grep -Rnw 'c:/users/bobbi/data1' -e 'Guards'

This particular example will return all files in the directory c:/users/bobbi/data1 that contain the string ‘Guards’ somewhere in the file contents.

Here is what the various commands do:

  • R: Search “recursively”, i.e. search the entire directory
  • n: Return the line “number”
  • w: Match the whole “word” specified
  • e: Specifies the pattern to search for

The following example shows how to use this syntax in practice.

Example: Use grep to List All Files Containing Specific String

Suppose that we have a directory with the following path:

  • c:/users/bobbi/data1

We can use the ls command to list all files in this directory:

We can see that the directory contains the following three files:

  • team_info1.txt
  • team_info2.txt
  • team_info3.txt

We can use the cat command to view the contents of each file:

Suppose that we would like to return only the files that contain the string “Guards” somewhere in the file contents.

We can use the following syntax to do so:

grep -Rnw 'c:/users/bobbi/data1' -e 'Guards'

The following screenshot shows how to use this syntax in practice:

grep list all files containing string

This returns the files named team_info1.txt and team_info2.txt, which both contain the string “Guards” in the file contents.

Since we used the n command, the output also displays the line numbers where the string occurs in each file.

From the output we can see that the string “Guards” appears in line 1 of each file.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
Bash: How to Filter for Lines in File that Start with Specific String
Bash: How to Filter for Rows where Column is Not Empty

Leave a Reply