Linux – Sorting the output of ps does not work

linuxpssort

I want to sort the output of the following command based on pcpu:

ps -p 29492 -L -o pid,tid,psr,pcpu

I tried the following:

ps -p 29492 -L -o pid,tid,psr,pcpu --sort=pcpu

But it doesn't seem to work. How can I fix this?

Best Answer

It's likely that in your implementation of ps, sorting only applies to processes, not threads (see fancy_spew() in procps' display.c). As far as I can tell, if you want to sort threads you need to post-process the output; e.g.

ps -p 29492 -L -o pid,tid,psr,pcpu | sort -n -k4,4

but then the header line gets mixed up in the output. If you want to keep the header line, you can pull it out and print it separately:

ps -p 29492 -L -o pid,tid,psr,pcpu | sed -e1\!b -e'w /dev/fd/2' -ed | sort -n -k4,4

You can also simply drop the header line by specifying blank header values for all the output selectors:

ps -p 29492 -L -o pid=,tid=,psr=,pcpu= | sort -n -k4,4

In all these cases, you can reverse the sort by adding -r to the sort parameters. The sort order may be affected by LC_NUMERIC or LC_ALL; setting LC_ALL=C will sort values with a decimal point . correctly.

Related Question