[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]

    Search the Q&A Archives

How can I access 2 variables (declared in the command line...

<< Back to: comp.lang.awk FAQ

Question by llira
Submitted on 7/10/2003
Related FAQ: comp.lang.awk FAQ
Rating: Not yet rated Rate this question: Vote
How can I access 2 variables (declared in the command line using -v) in awk and use them as a pattern to be searched?

  This is the command I'm using:
cat adlog.gen.20030601 | awk -v typ=Skipped -v model=3CE -f param.awk
  And part of my code is:
/'"typ"'/ && /'"model"'/ {
  if (indice==0)


Answer by reynaldo
Submitted on 7/23/2003
Rating:  Rate this answer: Vote
I also had the same problem. I have found this example. My problem is solved, I think yours should be too.

Taken from: The GNU Awk User's Guide

"A better method is to use awk's variable assignment feature (see Assigning Variables on the Command Line) to assign the shell variable's value to an awk variable's value. Then use dynamic regexps to match the pattern (see Using Dynamic Regexps). The following shows how to redo the previous example using this technique:

echo -n "Enter search pattern: "
read pattern
awk -v pat="$pattern" '$0 ~ pat { nmatches++ }
       END { print nmatches, "found" }' /path/to/data

Now, the awk program is just one single-quoted string. The assignment -v pat="$pattern" still requires double quotes, in case there is whitespace in the value of $pattern. The awk variable pat could be named pattern too, but that would be more confusing. Using a variable also provides more flexibility, since the variable can be used anywhere inside the program--for printing, as an array subscript, or for any other use--without requiring the quoting tricks at every point in the program."


Your answer will be published for anyone to see and rate.  Your answer will not be displayed immediately.  If you'd like to get expert points and benefit from positive ratings, please create a new account or login into an existing account below.

Your name or nickname:
If you'd like to create a new account or access your existing account, put in your password here:
Your answer:

FAQS.ORG reserves the right to edit your answer as to improve its clarity.  By submitting your answer you authorize FAQS.ORG to publish your answer on the WWW without any restrictions. You agree to hold harmless and indemnify FAQS.ORG against any claims, costs, or damages resulting from publishing your answer.


FAQS.ORG makes no guarantees as to the accuracy of the posts. Each post is the personal opinion of the poster. These posts are not intended to substitute for medical, tax, legal, investment, accounting, or other professional advice. FAQS.ORG does not endorse any opinion or any product or service mentioned mentioned in these posts.


<< Back to: comp.lang.awk FAQ

[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]

© 2008 FAQS.ORG. All rights reserved.