Match columns and print specific field

Hello,

I have data in following format.

pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,

main,FRONTEND,,,0,3,15000,61,13752,14647,0,0,1,,,,,OPEN,,,,,,,,,1,1,0,,,,0,0,0,12,,,,0,60,0,1,0,0,,0,12,61,,,
apache2,elb0,0,0,0,1,,3,687,723,,0,,0,0,0,0,UP,1,1,0,0,0,45,0,,1,2,1,,3,,2,0,,1,L4OK,,0,0,3,0,0,0,0,0,,,,0,0,
apache2,elb1,0,0,0,1,,3,687,723,,0,,0,0,0,0,UP,1,1,0,0,0,45,0,,1,2,2,,3,,2,0,,1,L4OK,,0,0,3,0,0,0,0,0,,,,0,0,
apache2,elb2,0,0,0,1,,3,687,723,,0,,0,0,0,0,UP,1,1,0,0,0,45,0,,1,2,3,,3,,2,0,,1,L4OK,,0,0,3,0,0,0,0,0,,,,0,0,
apache2,elb3,0,0,0,1,,3,687,723,,0,,0,0,0,0,UP,1,1,0,0,0,45,0,,1,2,4,,3,,2,0,,1,L4OK,,0,0,3,0,0,0,0,0,,,,0,0,
apache2,elb4,0,0,0,1,,3,687,723,,0,,0,0,0,0,UP,1,1,0,0,0,45,0,,1,2,5,,3,,2,0,,1,L4OK,,0,0,3,0,0,0,0,0,,,,0,0,
apache2,BACKEND,0,0,0,3,0,60,13752,14460,0,0,,0,0,0,0,UP,24,24,0,,0,45,0,,1,2,0,,60,,1,0,,12,,,,0,60,0,0,0,0,,,,,0,0,

Now I want to print "slim" value for "main,FRONTEND" or "ereq" value for "apache2,elb4" or process data in similar fashion. I tried below command but it prints entire column.

#awk -F, '/main,FRONTEND/{print}' socat.txt 

it prints entire line which has around 51 fields, among that one value carries "slim" field value.I dont know field number of "slim". I want to print "slim" value of "main,FRONTEND" column. Giving field number to awk can work but since there are lots of fields and elbs I dont want to use that option.

Thanks,
Pushpraj

awk -F ',' 'NR == 1{for(i=1; i<=NF; i++) a[$i] = i; next}
 /^main,FRONTEND/ {print $(a["slim"])}
 /^apache2,elb4/ {print $(a["ereq"])}' socat.txt
1 Like

Thanks Srini, Its working fine :slight_smile:
I have one query, What needs to be done if I have to send matching strings as a variable to same awk command. My variable would be like mentioned below

proxy="main,FRONTEND"
field="slim"

These variable will be set in shell script and awk will refer it accordingly.
How do I integrate these variable into the same command which you have provided.

Thanks Again,

Pushpraj

awk -F ',' 'NR == 1{for(i=1; i<=NF; i++) a[$i] = i; next}
 $0 ~ "^" proxy {print $(a[field])}' proxy="main,FRONTEND" field="slim" socat.txt
1 Like

Thanks, code is working fine. Now I am facing another issue with exact string match.
if my variable value is "apache2,elb1" and the file contains lines like "apache2,elb1" "apache2,elb11" "apache2,elb12"
In this case code fetching values for all the 3 lines rather than just "apache2,elb1"

Thanks,
Pushpraj

Please use code tags as required by forum rules!

Try (untested): $0 ~ "^" proxy FS {...

1 Like

Thanks, It worked :slight_smile: :slight_smile: