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

4 comments:

prasad said...

plc .help me solve this problem

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

prasad said...

how to do ....

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

Jadu Saikia 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

© Jadu Saikia www.UNIXCL.com