Search code examples
bashawknewlineeol

Awk multiple columns of top


On RedHat, using this command (top ten cpu users):

top -n 1 -b -c|head -17|tail -11

I would only need the PID, USER, %CPU, %MEM, TIME+, & COMMAND columns

Ideally, I would like tabs between the first columns then the COMMAND column printing normally with space delimiters.

So, something similar to:

top -n 1 -b -c|head -17|tail -11|awk '{print $1"\t"$2"\t"$9"\t"$10"\t"$11"\t"} {for (i=12;i<=NF;i++) printf("%s ",$i)} {print ""}'

However, a newline occurs between the two print statements.

EXAMPLE OUTPUT:

PID     USER    %CPU    %MEM    TIME+     COMMAND
15968   root    17.8    0.0     0:00.11   /usr/local/bin/pmun -p -h vm21fc root
15962   igsg093 16.2    0.1     0:00.16   top -n 1 -b -c
15966   idig056 6.5     0.1     0:00.04   /usr/bin/perl -w /scripts/script.pl arg
15969   root    6.5     0.1     0:00.04   pmasterd -ars
1       root    0.0     0.0     0:03.37   init [3]
2       root    0.0     0.0     3:38.62   [migration/0]
3       root    0.0     0.0     0:29.41   [ksoftirqd/0]
4       root    0.0     0.0     0:00.00   [watchdog/0]
5       root    0.0     0.0     0:03.70   [events/0]
6       root    0.0     0.0     0:00.00   [khelper]

Any assistance would be appreciated. Thanks!

.

BONUS help: If possible to cut the output of characters of the second print statement (for COMMAND) to a certain length, that may be helpful too.


Solution

  • You can make use of the OFS (Output Field Separator) variable so that print handles the tabs for you:

    top -n 1 -b -c| awk -vOFS="\t" 'NR>6 && NR<18 {s=""; for (i=12;i<=NF;++i) s=s FS $i; print $1,$2,$9,$10,$11,s}'
    

    Comma separated arguments are printed with the OFS in between them.

    If you would like to limit the length of s, you could take a substr of s in the print statement:

    print $1,...,substr(s,0,N)
    

    Where N is the maximum length of the the command.