user1926550
user1926550

Reputation: 695

Sorting by integer value

I am writing a bash script and I am using

ps -e -o %cpu

command.

I would like to have output of sorted %cpu values (descending). How to do that? I know that I should use sort command but I don't know how.

Upvotes: 8

Views: 21612

Answers (2)

perreal
perreal

Reputation: 97938

ps -e -o %cpu | sort -nr

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

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

Upvotes: 17

n3rV3
n3rV3

Reputation: 1106

ps has an inbuilt option that sorts its output, based on any field of choice. You can use

ps k -%cpu -e -o %cpu

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

If you omit the - in front of the sort field then it will be sorted in ascending order. Also note that you can give it multiple sort fields:

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

This sorts the output(in descending order for both) first based on the %cpu field and second based on %mem field.

Upvotes: 1

Related Questions