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.
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.
Here's the syntax to pass variables (and a few awk-style issues fixed):
awk -v filename="${filename}" '$9 == filename { print "File exists" }'
ENVIRON
instead
– Stéphane Chazelas
Mar 22 '15 at 08:38
$9
will only compare against the first part of the filename. But this can be easily fixed by using plainls
(and comparing against$1
in awk) instead of usingls -l
. – Janis Mar 22 '15 at 05:41stat
command available (instead ofls
); 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