2

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
upog
  • 4,965
  • 8
  • 42
  • 81
  • possible duplicate of [Can we use shell variables in awk?](http://stackoverflow.com/questions/15786777/can-we-use-shell-variables-in-awk) – tripleee Jan 02 '14 at 19:04
  • What are you trying to achieve? Do you want to print a line 10 times to a new file if field number 27 is equal to `"addr1"`? – Håkon Hægland Jan 02 '14 at 19:13

4 Answers4

5

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
chepner
  • 497,756
  • 71
  • 530
  • 681
2

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
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
1

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
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
1

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 .

Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52