How to Use Case-Insensitive Search and Replace in sed


Often you may want to use a case-insensitive search and replace with sed.

The easiest way to do so is by using a capital letter I as follows:

sed 's/Mavs/Mavericks/I' nba_teams.txt

This particular example replaces each occurrence of Mavs with Mavericks regardless of case in the file named nba_teams.txt.

Note that we use the s command in sed in to “substitute” one pattern for another pattern.

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

Example: Use Case-Insensitive Search and Replace in sed

Suppose that we a file named nba_teams.txt that contains the names of various NBA basketball teams.

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

case-insensitive search and replace in sed

Suppose that we would like to replace each occurrence of Mavs with Mavericks in the file.

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

sed 's/Mavs/Mavericks/' nba_teams.txt

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

Notice that only the occurrences of Mavs with the exact matching case have been replaced.

This is because sed uses case-sensitive search and replace by default.

To instead perform a case-insensitive search and replace, we can use the following syntax:

sed 's/Mavs/Mavericks/I' nba_teams.txt

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

sed case-insensitive search and replace

Notice that each occurrence of Mavs has been replaced with Mavericks, regardless of case.

Note that if you would like to modify the file in-place then you can add the -i flag as follows:

sed -i 's/Mavs/Mavericks/I' nba_teams.txt

This will make the search and replacement in the file in-place.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace Tab Characters
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply