Bash: How to Check if File Contains Specific String


Often you may want to use Bash to check if a file contains a specific string.

There are two easy ways to do so:

Method 1: Check if File Contains Specific String

grep -q "Miami" cities.txt && echo "Yes" || echo "No"

This particular example will check if the file named cities.txt contains the string “Miami” and will return “Yes” or “No” as a result.

Method 2: Check if File Contains One of Several Specific Strings

grep -qE "Miami|Portland" cities.txt && echo "Yes" || echo "No" 

This particular example will check if the file named cities.txt contains the strings “Miami” or “Portland” and will return “Yes” or “No” as a result.

Here are what the various grep commands do:

  • -q: Tells grep to exit with a success exit code as soon as one occurrence of the pattern is detected in the file.
  • -E: Tells grep to interpret the pattern as an extended regular expression.

The following examples show how to use each of these methods in practice.

Example 1: How to Check if File Contains Specific String Using Bash

Suppose that we have a file named cities.txt saved on our computer that contains the names of various U.S. cities.

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

Suppose that we would like to check if the file contains the string “Miami” or not.

We can use the following syntax to do so:

grep -q "Miami" cities.txt && echo "Yes" || echo "No"

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

Bash check if file contains string

This returns “Yes” since the file does indeed contain the string “Miami” on several lines.

Suppose we instead use the following syntax to check if the file contains “Portland” on any line:

grep -q "Portland" cities.txt && echo "Yes" || echo "No"

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

This returns “No” since the file does not contain the string “Portland” on any line.

Example 2: How to Check if File Contains One of Several Specific Strings Using Bash

Suppose that we would like to check if the file named cities.txt contains either “Miami” or “Portland” anywhere in the file.

We can use the following syntax to do so:

grep -qE "Miami|Portland" cities.txt && echo "Yes" || echo "No"

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

Bash check if file contains one of several strings

This returns “Yes” since the file contains at least one of these strings in the file.

Related Tutorials

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

Bash: How to Check if File is Empty
Bash: How to Count Number of Columns in File
Bash: How to Replace All Occurrences of String in File

Leave a Reply