user583507
user583507

Reputation:

regular expression matching with awk

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.

Upvotes: 1

Views: 1499

Answers (5)

glenn jackman
glenn jackman

Reputation: 246807

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

Upvotes: 2

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

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.

Upvotes: 0

Kent
Kent

Reputation: 195059

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.

Upvotes: 1

don_jones
don_jones

Reputation: 852

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

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

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

Upvotes: 1

Related Questions