This question already has an answer here:

How to use a value of a variable in awk? Something like this:

    filename = "test.txt"
    ls -l | awk '{ if ($9 == filename) print("File exists")}'

I can't use $ in awk to access the value of that variable.

marked as duplicate by jasonwryan, mdpc, Michael Homer, Anthon, Archemar Mar 22 '15 at 9:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • @ABC; note that your code is not robust; if the filename contains spaces then $9 will only compare against the first part of the filename. But this can be easily fixed by using plain ls (and comparing against $1 in awk) instead of using ls -l. – Janis Mar 22 '15 at 5:41
  • Yeah. You are right, but I need besides name and size. That is just a part of code. – ABC Mar 22 '15 at 5:46
  • 1
    Note, there's also the stat command available (instead of ls); e.g. stat -c "%s %n" files..., and you can use your own formatting (incl. delimiters, quoting) so that any subsequent (awk-) processing becomes more robust. – Janis Mar 22 '15 at 6:06

Here's the syntax to pass variables (and a few awk-style issues fixed):

awk -v filename="${filename}" '$9 == filename { print "File exists" }'
  • 2
    Note that you cannot use -v for arbitrary content as awk expands backslash escape sequences in them. best is to use ENVIRON instead – Stéphane Chazelas Mar 22 '15 at 8:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.