How to search by variable in awk

时间秒杀一切 提交于 2019-12-24 00:34:51

问题


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 ?


回答1:


Use the awk matching operator instead of the slashes:

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



回答2:


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

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



回答3:


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}'


来源:https://stackoverflow.com/questions/7820115/how-to-search-by-variable-in-awk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!