-1

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.

ABC
  • 209
  • @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 05:41
  • Yeah. You are right, but I need besides name and size. That is just a part of code. – ABC Mar 22 '15 at 05: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 06:06

1 Answers1

2

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

awk -v filename="${filename}" '$9 == filename { print "File exists" }'
Janis
  • 14,222