How to Use grep with Case-Insensitive Matching


Often you may want to use the grep command in Bash to search for patterns in a file based on case-insensitive matching.

You can use the -i flag to do so:

grep -i "Mavs" points.txt

This particular example will return all lines that contain the pattern “Mavs” (regardless of case) in the file named points.txt.

By using the -i flag, we specify that we would like to find the pattern “Mavs” using a case-insensitive search.

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

Example: How to Use grep with Case-Insensitive Matching

Suppose that we have a filed named points.txt that contains information about points scored by basketball players on various teams.

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

The first field in each line contains the name of the team the player is on and the second field contains the points scored by the player.

Suppose that we would like to return all lines that contain the pattern “Mavs” somewhere in the line.

Suppose we attempt to use the following syntax to do so:

grep "Mavs" points.txt 

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

By default, grep returns only the lines that match the exact case of the pattern “Mavs” in the line.

However, we can use the -i flag to make this search case-insensitive:

grep -i "Mavs" points.txt 

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

grep case-insensitive

Notice that this returns all lines in the file that contain the pattern “Mavs”, regardless of case.

Related Tutorials

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

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use sed to Replace Multiple Strings

Leave a Reply