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.
jl66Asked:
Who is Participating?
 
woolmilkporcCommented:
A first approach with "awk":

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

Open in new window

Add "> test_res.txt" at the end when you're satisfied with the outcome, but first please test by displaying the result at your terminal.
0
 
jl66Author Commented:
Thanks a lot.
0
 
woolmilkporcCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.