Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find and replace specific entries in awk

Status
Not open for further replies.

Eric33

Technical User
Sep 10, 2003
22
SG
I am newbie writing a awk script that read dynamically assigned variables from shell, and perform the following logic:
1. if Field1=var1 and Field2=var2, extract Field3
(i)if Field3 contains "%1" or "%2"..."%n" (not determinate), replace with corresponding fields from var3 before output Field3
(ii)if no "%n" found, output Field 3

2. if no match, output var3

I written a partial script to match the fields but have difficulty with the replacing the "%n" porttion.

Any help is much appreciated. Thanks in advance! This is what I have so far.

ie

var1=\"young\"
var2=\"girl\"
var3=\"shells/hawiian sea/shore\"

nawk -F, 'BEGIN {Counter = 0} {if (($1 == tolower('"$var1"')) && ($2 == tolower('"$var2"'"))) {print $3; Counter = 1}} END {if (Counter ==0) print '"$var3"'} input_file

Input_file:
young,girl,she sells sea %1 by the %2 shore\r\n

Output:
she sells sea shells by the hawiian sea shore\r\n


 
This may do what you want. I did it under DOS so I hard-coded the variables instead of using variable substitution. You could use the -v flag to pass the shell variables

nawk -v v1=$var1 -v v2=$var2 -v v3=$var3 -F,

BEGIN {
if (!v1) v1 = tolower("young")
if (!v2) v2 = tolower("girl")
if (!v3) v3 = "shells/hawiian sea/shore"
n3 = split(v3,a3,"/")
}
{
if (($1 == v1) && ($2 == v2)) {
while (match($3,"%")) {
j = RSTART+1
k = match(substr($3,j),/[0-9]*/)
m = substr($3,j,k)+0
sub(/%[0-9]*/,a3[m],$3)
}
print $3
}
else
print v3
}

CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
Thanks CaKiwi. The replacement algorithm works great! However, I have problem passing the variables using the -v option. Somehow, the variables is not passed in properly. Anyway, it is easily workaround using the in-line substitution.

Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top