kofucii
kofucii

Reputation: 7663

How to search by variable in awk

I'm trying to get the N-th row after a given pattern with awk. The problem is that awk searches pattern literally:

awk -v patt=${1} -v rows=${2}'NR==p {print} /patt/ {p=NR+rows}'

How to escape the "patt" valiable ?

Upvotes: 3

Views: 17276

Answers (3)

glenn jackman
glenn jackman

Reputation: 247210

Use the awk matching operator instead of the slashes:

awk -v patt=${1} -v rows=${2} 'NR==p {print} $0 ~ patt {p=NR+rows}'

Upvotes: 6

kofucii
kofucii

Reputation: 7663

I've maneged to get it work,with double quotes

patt=${1}
awk -v rows=${2} "NR==p {print} /${patt}/ {p=NR+rows}" $3

Upvotes: 2

Michael J. Barber
Michael J. Barber

Reputation: 25052

There's nothing special about the string containing the awk program, so you can build it as usual in the shell, e.g.:

awk -v rows=${2}'NR==p {print} /'"$1"'/ {p=NR+rows}'

Upvotes: 1

Related Questions