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
2
  • possible duplicate of Can we use shell variables in awk? Commented Jan 2, 2014 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"? Commented Jan 2, 2014 at 19:13

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.