how to using variables in search pattern in awk script

邮差的信 提交于 2021-01-28 07:10:59

问题


I want to print the pid when finding matched process while the match pattern is inputted:

ps aux | awk -v in="$1" '/in/{print $1}'

It seems the former awk sentence is not right. After checking many results in google like this, I change my script in the following but still cannot work:

ps aux | awk -v in="$1" '/$0 ~ in/{print $1}'

or

ps aux | awk -v in="$1" '($0 ~ in) {print $1}'

回答1:


You are fairly close in all your attempts. Problem is that in is a reserved keyword in awk.

You can use:

ps aux | awk -v var="$1" '$0 ~ var {print $1}'

Or else non-regex way:

ps aux | awk -v var="$1" 'index($0, var) {print $1}'


来源:https://stackoverflow.com/questions/42131314/how-to-using-variables-in-search-pattern-in-awk-script

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