Friday, April 11, 2008

Using Awk to Grab a Column

A lot of times when hacking on the command-line, I need to filter a particular column coming in from a pipe. A good example would be grabbing a pid from ps output or cat'ing a file with mysql process status and grabbing mysql thread id's for a subsequent kill. I generally use awk to do this because it's installed everywhere, and it makes doing this very simple. Take the following example: [~]# ps aux
root 2 0.0 0.0 0 0 ? S Mar09 1:04 [migration/0]
root 3 0.0 0.0 0 0 ? SN Mar09 0:10 [ksoftirqd/0]
root 4 0.0 0.0 0 0 ? S Mar09 1:14 [migration/1]
root 5 0.0 0.0 0 0 ? SN Mar09 0:10 [ksoftirqd/1]

Now to grab the pid's (2,3,4,5):

[~]# ps aux | awk '{print $2}'


One step further to kill those pid's (you wouldn't want to kill these, but...)

[~]# ps aux | awk '{print $2}' | xargs kill -15


Steve Laniel said...

I squirm away from awk. I prefer to use sed and cut here:

ps aux |sed 's#\s\+#\t#g' |cut -f2,3,4,5

If awk is everywhere, then sed and cut are super-extra-everywhere. I find this solution more portable.

Travis Whitton said...

Ooh, good stuff man. Point taken on sed and cut being even more ubiquitous. You'd be hard pressed to find a Unix based system without them. I appreciate the comments.

Olsson / Sweden said...

Awk has it's strength and sed has it's. Awk is much simpler for certain things so why not using it? When things get more complicated stay away from both awk and sed and use perl!