user43102
user43102

Reputation: 83

how to search a pattern using regex and append something to it using awk?

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

Answers (5)

Claes Wikner
Claes Wikner

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

VIPIN KUMAR
VIPIN KUMAR

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

aalku
aalku

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

Inian
Inian

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

Kent
Kent

Reputation: 195229

Take the right one you need:

You may want to have this?

awk -F'/' '$NF~/^Io/{$0=$0"_reg"}7' 

If you just want to check the pattern in whole line, then:

awk -F'/' '/Io/{$0=$0"_reg"}7' 

If take your input/output example, this line should go:

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

Related Questions