MrHappyAsthma
MrHappyAsthma

Reputation: 6522

Linux Shell - Find Top k Number Of Processes

I am trying to figure out how to get the top k number of processes in a linux shell. Obviously the first thing that popped into my head is top, but it does not seem to have any parameter to specify the number of processes to print.

Using batch mode and number of iterations parameters, I can get it to produce one iteration of all the processes and store the output, but I cannot find a way to abridge the list to a certain number. (Granted I could just get the whole list and crop it off, but the system I am using it on has 27000 processes running, so it takes a few seconds to retrieve the list).

Example:

>top -b -n1
>... (lots more processes here)
>26416 mcm101    20   0  4188  176   96 S  0.0  0.0   0:00.00 character_count
>26604 root      20   0  180m 5684 3532 S  0.0  0.0   0:00.54 sshd
>26616 pwf7      20   0  105m 1792 1432 S  0.0  0.0   0:00.10 bash

What I want is something like this:

>top k
>1 mcm101    20   0  4188  176   96 S  0.0  0.0   0:00.00 character_count
>2 pwf7      20   0  105m 1792 1432 S  0.0  0.0   0:00.10 bash
>... (more processes here)
>k root      20   0  180m 5684 3532 S  0.0  0.0   0:00.54 sshd

Does anyone know how to use top or any other command(s) to achieve this result?

Upvotes: 1

Views: 2149

Answers (1)

thkala
thkala

Reputation: 86333

How about this:

top -b -n1 | grep '^ *[0-9]' | head -n $k

top will output all processes in order of CPU usage, grep will select those lines from the output that start with a number (i.e. those that start with a PID) and head will output the first k lines from that output.

Upvotes: 2

Related Questions