user117974
user117974

Reputation: 431

Awk with a variable

I have an awk command to print out the total number of times "200" occurred in column 26.

awk '$26 ~ /200/{n++}; END {print n+0}' testfile

How do I modify this statement so I can pass 200 as a variable? e.g. if I have a variable $code with a value of 200

Thanks in advance

Upvotes: 0

Views: 162

Answers (2)

Kent
Kent

Reputation: 195269

awk  -v var="$shellVar" '$26~var{n++} END{print n}' file

you see above line how to use shell variable in awk. some notes for your awk one-liner:

  • print n+0 not necessary. because the n defined by you, not picked from input text, and you explicitly did n++, so it is number type, n+0 makes no sense

  • the ; before END should be removed

  • I copied your code about the checking 200 part. but it is risky. if the $26 has only a number, you can consider to use 1*$26 == 200 or $26 == "200" using regex in this situation may give wrong result, think about in your $26, value was : 20200

Upvotes: 2

Zombo
Zombo

Reputation: 1

awk '$26 ~ code {n++} END {print n+0}' code=200 testfile

If a filename on the command line has the form var=val it is treated as a variable assignment. The variable var will be assigned the value val.

§ Awk Program Execution

Upvotes: 3

Related Questions