Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to using variables in search pattern in awk script

Tags:

bash

shell

awk

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}'
like image 333
vinllen Avatar asked Sep 11 '26 08:09

vinllen


1 Answers

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}'
like image 50
anubhava Avatar answered Sep 13 '26 06:09

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!