upog
upog

Reputation: 5526

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

Upvotes: 2

Views: 2306

Answers (4)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14975

You can use a simply trick : break the awk code enclosure (single quotes) to put what you want inside, a piece of embedded code.

> a=10                                                                                                          
> awk 'BEGIN{for (i=0;i<='${a}';i++){printf("%d ", i)}}'
0 1 2 3 4 5 6 7 8 9 10 

The good: Simple and handy.

The bad: It makes your program less readable .

Upvotes: 1

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40778

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

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 81052

You use the -v argument to awk to pass in values from the outside as awk variables.

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

Upvotes: 1

chepner
chepner

Reputation: 532538

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

Upvotes: 5

Related Questions