0

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

1
  • If code has the value 20 and the number 200 appears in field 26, should that match or not? Are you looking for a match on the WHOLE of field 26 or only part of it? Commented Feb 5, 2014 at 23:40

2 Answers 2

3
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

Sign up to request clarification or add additional context in comments.

2 Comments

That's something I didn't know, but wanted to note after looking it up in The AWK Programming Language: the filename var=val assignment is performed at the time when that argument would otherwise be accessed as a file. This type of assignment allows variables to be changed before and after a file is read. Meaning that order is important.
@n0741337 Correct and variables assigned that way are not available in the BEGIN section which can cause confusion/mistakes. You should only use this method if you need to change a variables value between files, otherwise awk -v awkvar="$shellvar" is almost always the right approach. See the article I wrote for the comp.unix.shell FAQ at cfajohnson.com/shell/cus-faq-2.html#Q24 for more details.
2
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

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.