Link to home
Start Free TrialLog in
Avatar of jl66
jl66Flag for United States of America

asked on

global replace in shell

Have a question as follows:

cat test.txt

A '10 AB C test cat;'
B 231231 AB D dog;
D A B "C 10 20 30"
F '1111 AB C fish;'
...

Can we test to see if there is a pattern in a line such as "AB C", the last word will be replaced with X while the other lines are unchanged. The result will be

cat test_res.txt

A '10 AB C test X;'
B '231231 AB' D dog;
D A B "C 10 20 30"
F '1111 AB C X;'
...

Can any gurus shed some light on it with linux shell or awk? Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jl66

ASKER

Thanks a lot.
Thx for the points!

Here is a slightly enhanced version which will take into account something like this:

A '10 AB C test cat ; '

PAT="AB C"
REP="X"
awk -v P="$PAT" -v R="$REP" '{if($0~P) {F=NF; for(C=NF;C>1;C--) {if($C!~"[0-9a-zA-Z]") {F--}} sub("[0-9a-zA-Z]*",R,$F)} print}' test.txt

Open in new window

The first version was already able to handle

A '10 AB C test cat ;'

i. e. a space in front of ";", but not the additional space between ";" and the single quote.