Sed for selective pattern replacement

Hi

I am having a code snippet

grant permission to all user
sts|ln|uSe|PSG
sajncht|se|Use|PPSPSG
psg|ln|use|TSPSG
sts_user.Me revoke

I need to change all occurance of use (uSe,Use,use) with USE. I am using the following sed command for this

sed 's/[uU][sS][eE]/USE/g' s_sample.txt

Output:

grant permission to all USEr
sts|ln|USE|PSG
sajncht|se|USE|PPSPSG
psg|ln|USE|TSPSG
sts_USEr.Me revoke

Whereas desired output is as follows

grant permission to all user
sts|ln|USE|PSG
sajncht|se|USE|PPSPSG
psg|ln|USE|TSPSG
sts_user.Me revoke

It has to be done with a shell script. If somebody can provide a sed command it would be a gr8 help.

Thanks

# sed 's/\<[uU][sS][eE]\>/USE/g' s_sample.txt
grant permission to all user
sts|ln|USE|PSG
sajncht|se|USE|PPSPSG
psg|ln|USE|TSPSG
sts_user.Me revoke
2 Likes

Could you please explain the \< and \> ? I have been using sed for some time now but never came across these...

You specify a "word" with the pointed brackets.
Check this out:
GREP for Linguists
See 2.1, Trick #2.

1 Like

Note: \< an \> are GNU extensions..

--
awk version:

awk '{for(i=1;i<=NF;i++)if(toupper($i)==s)$i=s}1' FS=\| OFS=\| s=USE infile
1 Like

Alternatively..

sed 's/\([^a-zA-Z ]\)[uU][sS][eE]\([^a-zA-Z ]\)/\1USE\2/' inputfile

perl -lne 's/\buse\b/USE/i;print' inputfile

or try with word boundaries (for Gnu sed (* gsed) and ssed(super sed) and latest sed(like sed15..)

# sed 's/\b[uU][sS][eE]\b/USE/g' infile
grant permission to all user
sts|ln|USE|PSG
sajncht|se|USE|PPSPSG
psg|ln|USE|TSPSG
sts_user.Me revoke

regards
ygemici

With GNU sed, you can also do this:

sed 's/\<use\>/\U&/gi' infile

or

sed 's/\buse\b/\U&/gi' infile