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.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

A first approach with "awk":

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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jl66Author Commented:
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 ; '

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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Shell Scripting

From novice to tech pro — start learning today.