Reputation: 83
I'm trying to search a pattern using regex and once found wanted to append something to using awk
.
Example:
abc/def/ghi/jkl/Io_LogUserVal[29]
Expected:
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
I tried
awk -F "/" '{gsub(/Io_(\w+)/,$NF"_reg"); print$0}'
Upvotes: 1
Views: 67
Reputation: 1517
echo "abc/def/ghi/jkl/Io_LogUserVal[29]"| awk '{sub(/Val\[/,"Val_reg[")}1'
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
Upvotes: 0
Reputation: 3147
Solution with sed -
echo "abc/def/ghi/jkl/Io_LogUserVal[29]"| sed 's/Io_LogUserVal/Io_LogUserVal_reg/g'
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
echo "abc/def/ghi/jkl/Io_LogUserVal[29]"| sed '/Io/s/UserVal/UserVal_reg/g'
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
Upvotes: 0
Reputation: 2878
You can use &
to be replaced by the matched block.
awk '{gsub(/Io_(\w+)/,"&_reg"); print$0}'
If you want to replace only on the last field you can do it this way, adding -v OFS="/"
and $NF
:
awk -F "/" -v OFS="/" '{gsub(/Io_(\w+)/,"&_reg", $NF); print$0}'
Upvotes: 0
Reputation: 85865
Using GNU Awk gensub() function to use a regex match,
awk '{$NF=gensub(/^(.+)_(.+)\[(.+)\]$/,"\\1_\\2_reg[\\3]","g",$NF);}1' file
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
Once you match the last field ($NF
) with the regex (.+)_(.+)\[(.+)\]
modify the captured groups as you wish. (.+)
represents match any character multiple times.
Upvotes: 1
Reputation: 195229
Take the right one you need:
awk -F'/' '$NF~/^Io/{$0=$0"_reg"}7'
awk -F'/' '/Io/{$0=$0"_reg"}7'
kent$ awk -F'/' -v OFS="/" '$NF~/^Io/{sub(/\W/,"_reg&",$NF)}7'<<<"abc/def/ghi/jkl/Io_LogUserVal[29]"
abc/def/ghi/jkl/Io_LogUserVal_reg[29]
Upvotes: 0