Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a variable in awk to refer to a field's contents

It may be duplicate question, as I saw many with same title, but I cant find the error in my script by those questions…

My file is

for (( c=15; c<=60; c++ ))
do 
while read -r i
do
   echo $i | awk -v var="$c" -F, 'var ~ /@/ {print $0}' >> $c.csv
done < asia.csv
done

when I run like sh -x clean.sh

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

it show

+ read -r i
+ awk -v var=15 -F, 'var ~ /@/ {print $0}'
+ echo bellerock-casino.asia,CSC Corporate Domains R25-ASIA '(299),dcs-admin@curacaohosting.com,,DNS1.CURACAOHOSTING.COM|DNS.CURACAOHOSTING.COM|DNS.CURACAOHOSTING.NET|,,20-Jan-2014' 15:34:56 UTC,01-Mar-2015 20:05:35 UTC,,2014-01-20 15:34:56 UTC,2015-03-01 20:05:35 UTC,CLIENT TRANSFER PROHIBITED,2014-04-17 07:00:00 UTC,Registrant Name:Limited 'Cassini|Registrant' Organization:Cassini 'Limited|Registrant' Address:PO Box 606 Mezzanine 'West|Registrant' 'City:Gibraltar|Registrant' 'Country/Economy:GB|Registrant' Postal 'Code:1000|Registrant' 'Phone:+44.7624496408|Registrant' 'FAX:+44.1481822895|Registrant' E-mail:dcs-admin@curacaohosting.com,dcs-admin@curacaohosting.com,Limited Cassini,Cassini Limited,PO Box 606 Mezzanine West,,,,Gibraltar,,1000,UNITED KINGDOM,441481822895,,447624496408,,Administrative Name:Toohey 'Michael|Administrative' Organization:Australasian Gaming Specialists Pty 'Limited|Administrative' Address:3 Kimberley 

for some reasons inside the ‘ ‘ var won’t print 15

Any idea why so…

i.e. my script is checking if 15th field (and so on 16,17,18th) has @ or not… if it is the whole result should print in 15.csv

which is empty at the moment…

>Solution :

If you want to check the 15th field instead of 15 itself, you should use $var, not just var.

awk -v var="$c" -F, '$var ~ /@/ {print $0}' <<<"$i" >>"$c.csv"

Consider shortening your loop to run awk only once per value of c, instead of once per line per value of c:

#!/usr/bin/env bash
for (( c=15; c<=60; c++ )); do 
  awk -v var="$c" -F, '$var ~ /@/ {print $0}' >"$c.csv" <asia.csv
done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading