Home > Blockchain >  Using a variable in awk to refer to a field's contents
Using a variable in awk to refer to a field's contents

Time:08-05

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

it show

  read -r i
  awk -v var=15 -F, 'var ~ /@/ {print $0}'
  echo bellerock-casino.asia,CSC Corporate Domains R25-ASIA '(299),[email protected],,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:[email protected],[email protected],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...

CodePudding user response:

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
  • Related