Friday, October 16, 2009

There are many ways to grab a column

There are lots of utilities available when writing scripts to parse various data. A few of them can perform the same tasks. Here we will look at awk, colrm, and cut, and look at how they can all grab columns of data. I'll use 'ps aux' as the data source.

daniel@twilight:~$ ps aux|grep apache
root      5504  0.0  1.0  28092 11372 ?        Ss   Oct11   0:04 /usr/sbin/apache2 -k start
www-data 14227  0.0  2.4  44076 25736 ?        S    Oct14   1:33 /usr/sbin/apache2 -k start
www-data 14695  0.0  2.2  41644 23448 ?        S    Oct14   1:14 /usr/sbin/apache2 -k start
www-data 15563  0.0  2.5  44864 26572 ?        S    Oct14   1:16 /usr/sbin/apache2 -k start
www-data 18452  0.0  2.3  42780 24524 ?        S    Oct15   1:12 /usr/sbin/apache2 -k start
www-data 18770  0.0  2.1  41036 22456 ?        S    Oct15   0:46 /usr/sbin/apache2 -k start
www-data 18836  0.0  1.9  38520 20176 ?        S    Oct15   0:46 /usr/sbin/apache2 -k start
www-data 19174  0.0  1.8  37712 19080 ?        S    Oct15   0:47 /usr/sbin/apache2 -k start
www-data 20953  0.0  2.2  41152 22868 ?        S    05:45   0:16 /usr/sbin/apache2 -k start
www-data 21882  0.1  1.4  34580 14612 ?        S    11:42   0:00 /usr/sbin/apache2 -k start
www-data 21887  0.1  1.1  32112 12200 ?        S    11:43   0:00 /usr/sbin/apache2 -k start
daniel   21929  0.0  0.0   3008   756 pts/0    R+   11:47   0:00 grep apache

daniel@twilight:~$ ps aux | grep apache | awk '{print $1}'
root
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
daniel

daniel@twilight:~$ ps aux | grep apache | colrm 10
root
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
daniel

daniel@twilight:~$ ps aux | grep apache | cut -d" " -f1
root
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
www-data
daniel

Additional Reading:

http://www.shell-fu.org/lister.php?tag=colrm

http://linux.die.net/man/1/colrm

http://www.grymoire.com/Unix/Awk.html

http://sparky.rice.edu/awk.html

http://lowfatlinux.com/linux-columns-cut.html

http://www.computerhope.com/unix/ucut.htm

No comments:

Post a Comment