开发者

regular expression matching with awk

开发者 https://www.devze.com 2023-04-13 04:38 出处:网络
I\'m messing around a little with awk and I am still kind of new to bash/awk so bear with me when I do this to look for all processes running as root

I'm messing around a little with awk and I am still kind of new to bash/awk so bear with me

when I do this to look for all processes running as root

ps aux | awk '$0 ~ /.*root*./ {print $0, $开发者_开发问答11}'

it prints out everything as I expect, but it also prints out a line at the bottom that includes MY username (which isn't root) and the process awk. Why is that? What can I do about it?

Note: I'm not really interested in alternate solutions to print out all the processes that have root. I can already do that. I want to understand what is going on here and how I can use this.


The way to avoid the awk process from being printed is this:

ps aux | awk '/[r]oot/ {print $0,$11}'

That hack works like this: awk will be searching for the sequence of characters 'r' 'o' 'o' 't'. The actual awk process is not matched because the ps output contains the sequence of characters '[' 'r' ']' 'o' 'o' 't'.


There seem to be a couple of issues: One is that you have *. instead of .* after "root". The other is that you are searching the whole line and not just the column that contains the username.

$0 represents the entire line. $1 represents the first column.

Something closer to what you want would be

ps aux | awk '$1 ~ /.*root.*/ {print $0, $11}'

but you could also just do

ps aux | awk '$1=="root" {print $0, $11}'


To exactly match the first field you write

ps aux | awk '$1 == "root"' { print $0, $11 }'

you can also ask ps to filter for you

ps -Uroot | awk ' { print $5 } '


is this what you want?

ps aux | awk '$0 ~ /^root/ {print $0, $11}'

the reason that you have the "last line" is your regex was .root.. and your ps|awk line has the same string. so it is selected.

maybe you can with grep -v "awk" to filter your awk line out.


If you need to match only process owned by root (i.e. records beginning with the string root):

ps aux | awk '/^root/ { print $0, $11 }'

Note that /regex/ and $0 ~ /regex/ are equivalent.

0

精彩评论

暂无评论...
验证码 换一张
取 消