jl66
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Thx for the points!
Here is a slightly enhanced version which will take into account something like this:
A '10 AB C test cat ; '
A '10 AB C test cat ;'
i. e. a space in front of ";", but not the additional space between ";" and the single quote.
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
The first version was already able to handleA '10 AB C test cat ;'
i. e. a space in front of ";", but not the additional space between ";" and the single quote.
ASKER