Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using shell variable in awk

I am new to awk and need some help

this works

awk '{
for(i =0;i<10;i++){
if ($27 == 'addr1') {
    print >"temp.csv"
     }
    }
}' /tmp/input.csv

i tried below and is not working, how to pass count value from outside to awk command

count=10
echo $count
awk '{
for(i =0;i<count;i++){
if ($27 == 'addr1') {
    print >"temp.csv"
     }
    }
}' /tmp/input.csv
like image 656
upog Avatar asked Mar 10 '26 14:03

upog


2 Answers

Use the -v option to set a variable inside awk:

awk -v count="$count" '...'

"Filename" arguments of the form X=Y are also interpreted as variable assignments. The following should work:

awk '...' count="$count" /tmp/input.csv
like image 162
chepner Avatar answered Mar 12 '26 04:03

chepner


If you want compare against a string inside awk, you need double quotes around the string. Like

awk -v count=$count '
$27=="addr1" {
  for(i=0;i<count;i++)
     print > "temp.csv" 
}' /tmp/input.csv

(Note that for instance 'if ($27 == 'addr1')' will expand to 'if ($27 == addr1)', that is: addr1 without double quotes)

If you instead want compare against the shell variable $addr1 inside awk, you can do

awk -v count=$count -vaddr1="$addr1" '
$27==addr1 {
  for(i=0;i<count;i++)
     print > "temp.csv" 
}' /tmp/input.csv
like image 22
Håkon Hægland Avatar answered Mar 12 '26 02:03

Håkon Hægland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!