0

Possible Duplicate:
external variable in awk

How do I pass this variable below?

This doesn't work:

fname=testfile.txt
lsof | awk '/deleted/&&/$fname/ {print $4}'  *----no output*

While this works:

lsof | awk '/deleted/&&/testfile.txt/ {print $4}'
3r
munish
  • 7,825
  • 24
  • 71
  • 97

1 Answers1

2

This happens because shell variables are not expanded in single quotes. Use awk with -v to pass the pattern into awk like so:

fname=testfile.txt
lsof | awk -v pattern="$fname" '/deleted/ && $0 ~ pattern { print $4 }'
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Chris Down
  • 122,090
  • 24
  • 265
  • 262