sed: case insensitive actions (search replace delete..)

In this article I will show you different ways to perform an action (as per your requirement) ignoring the case of the letters to be searched in a file

Below is our sample file

# cat /tmp/file
one
Two
three
Three
two
One

 

Perform a case insensitive search and replace

By default if I do a normal search and replace it will look something like below. Here I am replacing "two" with "new-word"

# sed -e 's/two/new-word/g' /tmp/file
one
Two
three
Three
new-word
One

Let us perform the same for all the word "two" ir-respective of its case, this can be done using "I" as shown below

# sed -e 's/two/new-word/Ig' /tmp/file
one
new-word
three
Three
new-word
One

As you see all the occurrences of the word "two" is replaced with "new-word"

There are more ways to do this, for example you know that only one letter of the text you wish to replace may have different case so here

# sed -e 's/[tT]wo/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

If here are more than one letters which can be of different case then the same can be done accordingly using below

# sed -e 's/[tT][wW]o/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

To ignore case for all 3 letters

# sed -e 's/[tT][wW][oO]/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

To perform in-file replacement use below syntax

# sed -i 's/two/new-word/Ig' /tmp/file

OR

# sed -i 's/[tT][wW]o/new-word/g' /tmp/file

 

Perform a case insensitive search and delete

To perform a search and delete by default below syntax is used

# sed -e '/two/d' /tmp/file
one
Two
three
Three
One

To perform the same for all the word "two" ir-respective of its case use "I" as shown below

# sed -e '/two/Id' /tmp/file
one
three
Three
One

There are more ways to do this, for example you know that only one letter of the text you wish to delete may have different case so here

# sed -e '/[tT]wo/d' /tmp/file
one
three
Three
One

If here are more than one letters which can be of different case then the same can be done accordingly using below

# sed -e '/[tT][wW]o/d' /tmp/file
one
three
Three
One

To ignore case for all 3 letters

# sed -e '/[tT][wW][oO]/d' /tmp/file
one
three
Three
One

To perform in-file replacement use below syntax

# sed -i '/two/Id' /tmp/file

OR

# sed -i '/[tT][wW][oO]/Id' /tmp/file

 

Leave a Comment