Sort based on a column

You can use the `sort’ utility to sort not only on the first field, but also an arbitrary column. Take this output from ps:

[code lang=”bash”][kale@superhappykittymeow ~]$ ps ax -ly |grep httpd
R 502 10027 8387 0 78 0 668 979 – pts/1 0:00 grep httpd
S 502 10247 28321 0 76 0 16924 9961 semtim ? 1:58 /usr/sbin/httpd
S 0 28321 1 0 78 0 11564 7645 – ? 0:00 /usr/sbin/httpd
S 502 28327 28321 0 75 0 19152 10412 semtim ? 1:39 /usr/sbin/httpd
S 502 28328 28321 0 84 0 16628 9903 semtim ? 1:56 /usr/sbin/httpd
S 502 28331 28321 0 75 0 17108 9962 semtim ? 1:45 /usr/sbin/httpd
S 502 28332 28321 0 75 0 19152 10446 semtim ? 1:54 /usr/sbin/httpd
S 502 28333 28321 0 75 0 15692 9624 semtim ? 1:54 /usr/sbin/httpd
S 502 28334 28321 0 78 0 17476 10107 semtim ? 2:01 /usr/sbin/httpd
S 502 28335 28321 0 75 0 17460 10237 semtim ? 1:57 /usr/sbin/httpd
S 502 28336 28321 0 75 0 16836 9897 – ? 1:54 /usr/sbin/httpd
S 502 30058 28321 0 75 0 15248 9622 semtim ? 0:33 /usr/sbin/httpd
[/code]

This can be sorted by the SZ column, column 9, as such:

[code lang=”bash”][kale@superhappykittymeow ~]$ ps ax -ly |grep httpd |sort -nr -k 9n
R 502 10045 8387 0 78 0 668 979 – pts/1 0:00 grep httpd
S 0 28321 1 0 78 0 11564 7645 – ? 0:00 /usr/sbin/httpd
S 502 30058 28321 0 75 0 15248 9622 semtim ? 0:33 /usr/sbin/httpd
S 502 28333 28321 0 75 0 15692 9624 semtim ? 1:54 /usr/sbin/httpd
S 502 28336 28321 0 75 0 16836 9897 – ? 1:54 /usr/sbin/httpd
S 502 28328 28321 0 84 0 16628 9903 semtim ? 1:56 /usr/sbin/httpd
S 502 10247 28321 0 76 0 16924 9961 semtim ? 1:58 /usr/sbin/httpd
S 502 28331 28321 0 75 0 17108 9962 semtim ? 1:45 /usr/sbin/httpd
S 502 28334 28321 0 78 0 17476 10107 semtim ? 2:01 /usr/sbin/httpd
S 502 28335 28321 0 75 0 17460 10237 semtim ? 1:57 /usr/sbin/httpd
S 502 28327 28321 0 75 0 19152 10412 semtim ? 1:39 /usr/sbin/httpd
S 502 28332 28321 0 75 0 19152 10446 semtim ? 1:54 /usr/sbin/httpd
[/code]

The -k switch tells sort to sort based on a key, which we specify as 9n (column 9, numeric). Much easier to review the output.

Leave a Reply