Sort by integer value

I am writing a bash script and I am using

ps -e -o %cpu

teams.

I would like to have output of sorted %cpu values ​​(decreasing). How to do it? I know that I have to use the sort command, but I don't know how to do it.

+4
source share
2 answers
  ps -e -o %cpu | sort -nr 

n for numeric, r for the inverse. If you also want to remove the header:

  ps -e -o %cpu | sed '1d' | sort -nr 
+8
source

ps has a built-in parameter that sorts its output based on any selected field. you can use

 ps k -%cpu -e -o %cpu 

Here k sorts the output based on the provided field, and -%cpu - sort it in descending order.

If you omit - before the sort field, it will be sorted in ascending order. Also note that you can give it several sort fields:

 ps k -%cpu,-%mem -e -o %cpu,%mem 

This sorts the output (in decreasing order for both), first in accordance with the %cpu field, and the second in the %mem field.

+1
source

All Articles