Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
Getting the first 5 lines from PID and COMMAND using top

hi i'm struggling to figure out how to get the top 5 lines of the PID and COMMAND headers when opening top

at the moment im using

top | awk '{print $1,$2}NR==5{exit}'

this is obviously annoyingly giving me this:

Processes: 390
2021/12/17 13:47:48
Load Avg:
CPU usage:
SharedLibs: 146M
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

With your shown samples, please try following code. Since you need top 5 PIDs details so printing first 5 lines wouldn't work here. So skipping first 6 lines in output of top(which are about system details).

top -b | awk 'FNR>=7 && FNR<=12{print $1};FNR==12{exit}'

Explanation: Simple explanation of above code would be, passing top command's output to awk as an standard input. Then in awk program checking condition if line number is from 7th to 12th then print it and on 12th line exit out of program.

Where definition of top -b option is as follows from man top:

b :Batch-mode operation Starts top in Batch mode, which could be useful for sending output from top to other programs or to a file. In this mode, top will not accept input and runs until the iterations limit you've set with the `-n' command-line option or until killed.

over 4 years ago · Santiago Trujillo Report

0

Other Solutions:

top -b for batch mode
top -n 1 for a single shot (no loop)

Getting lines

  • with --> head -12 | tail -6
  • or --> awk 'FNR>=7 && FNR<=12'
  • or --> sed -n 7,12p

Print PID and Command

  • awk '{print $1, $NF}'

...

top -b|head -12|tail -6|awk '{print $1, $NF}'
top -b -n 1|awk 'FNR>=7 && FNR<=12{print $1, $NF}'
top -b -n 1|sed -n 7,12p|awk '{print $1, $NF}'
         


         
over 4 years ago · Santiago Trujillo Report

0

For MAC OS X, the command is:

top -a -n20 | awk 'FNR>=11 && FNR<=31{print $0};FNR==31{exit}' > cpustat.txt

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!