1

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?

2
  • 1
    How do you rank your k processes ? Commented Feb 9, 2013 at 20:55
  • By the %CPU field of the top command (which i believe is the default). Commented Feb 9, 2013 at 21:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I know thats kind of simple but I'm relatively new to linux commands so it seemed quite difficult! :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.