Tuesday, March 11, 2008

Case insensitive serach and replace:sed,awk


$ cat os.txt
unix
UNIX
Unix
uNiX

Intention: To replace all unix(s) in os.txt above with the word "BEST". As you can see all the 4 occurrences of the word "unix" is of different cases(upper,lower,mixed)

In general sed search and replace is "case sensitive". The below replacement is only going to effect the 1st line, not all.
$ sed 's/unix/BEST/' os.txt
BEST
UNIX
Unix
uNiX

Sed supports "i" or "I" for "case insensitive" search and replacement
$ sed 's/unix/BEST/i' os.txt
BEST
BEST
BEST
BEST

$ sed 's/unix/BEST/I' os.txt
BEST
BEST
BEST
BEST


This is one more way:
$ sed 's/[uU][nN][iI][xX]/BEST/' os.txt
BEST
BEST
BEST
BEST

With AWK, you have to make IGNORECASE=1 in BEGIN section
$ awk 'BEGIN{IGNORECASE=1} {sub(/unix/,"BEST");print}' os.txt
BEST
BEST
BEST
BEST

5 comments:

Prasad Tharanga said...

plc .help me solve this problem

i want to find a word in file and replace that line using bash script

Prasad Tharanga said...

how to do ....

find a text in a file and replace that line with another text

Unknown said...

@Prasad, Thanks for your comment. It would be very useful if you can provide me a sample file stating what you want to achieve. What I understood from your comment, you want to replace a line containing a particular pattern ?

Randy Harris said...

Thanks Jadu, this was very helpful, using SED with case insensitive.

A Bash question to pose if that is ok.

I have a variable VAR and based on that variable I know how to change VAR to all lower case, but I'm having trouble figuring how to to make a new variable, VARTC that takes the lower case VAR and changes it to Title Case.

i.e.: VAR="This is a variable name New York City"
VARTC would = "This Is A Variable Name New York City"

Better yet would be to leave existing capitalization and change any first characters of all words to Caps, such that:

VAR="This is a great country NZ"
VARTC would ="This Is A Great Country NZ"
(NZ remains call caps that way.)

Thanks much.

Randy

Unknown said...

There are certain things I don't want to joke about. If it's about somebody else, it's fine. If it's about me, I think it's totally insensitive! See the link below for more info.

#insensitive
www.ufgop.org

© Jadu Saikia www.UNIXCL.com