Chris
Chris

Reputation: 1019

pass shell variable into awk's patern search

In a script I want to search connections established between some ports gathered with another command and set on PORT variable and specific systems.

the PORT variable is pass to awk using -vp=${PORT}

but I don't know how to use "p" it inside the rest of the pattern. his does not work:

$ lsof -i -P|awk -vp=${PORT} '$(NF-1)~/vm7.+:'$p'->(vm9|vm11).+ESTABLISHED/{print $(NF-1)}'
$ lsof -i -P|awk -vp=${PORT} '$(NF-1)~/vm7.+:'p'->(vm9|vm11).+ESTABLISHED/{print $(NF-1)}'

Upvotes: 0

Views: 53

Answers (2)

James Brown
James Brown

Reputation: 37454

Use match:

$ awk -v p=$port 'match($(NF-1),"vm7.+:" p "->(vm9|vm11)"){print $(NF-1)}'

There might be some errors as there was no test material. Removed the ESTABLISHED as it is in $NF, not $(NF-1) (in my systems, at least).

... or don't:

$ awk -v p=$port '$(NF-1) ~ "vm7.+:" p "->(vm9|vm11)" {print $(NF-1)}'

Today I learned something.

Upvotes: 0

Kent
Kent

Reputation: 195209

give this a try:

awk -v p="$PORT" '{pat="yourHost(or whatever):"p}$(NF-1)~pat{print $(NF-1)}'
  • build the pattern(pat) with p and check the field (NF-1)
  • you don't need (shouldn't have) the ESTABLISHED in pattern, since it is the last field NF instead of NF-1

Upvotes: 1

Related Questions