Reputation: 2024
I use a specific ps command namely
ps -p <pid> -o %cpu, %mem
which gives me a result like
%CPU %MEM
15.1 10.0
All i want to do is to just print these numbers like 15.1 and 10.0 without the headers. I tried to use the 'cut' . But it seems to work on every line.
i.e
echo "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5
gives something like
%CPU
8.0
How to get just the numbers without the headers ?
Upvotes: 19
Views: 20836
Reputation: 16
You can use below command and you don't need to add pcpu="", it worked for me:
ps -Ao pcpu=
Upvotes: 0
Reputation: 365707
The BSD (and more generally POSIX) equivalent of GNU's ps --no-headers
is a bit annoying, but, from the man page:
-o Display information associated with the space or comma sepa- rated list of keywords specified. Multiple keywords may also be given in the form of more than one -o option. Keywords may be appended with an equals (`=') sign and a string. This causes the printed header to use the specified string instead of the standard header. If all keywords have empty header texts, no header line is written.
So:
ps -p 747 -o '%cpu=,%mem='
That's it.
If you ever do need the remove the first line from an arbitrary command, tail makes that easy:
ps -p 747 -o '%cpu,%mem' | tail +2
Or, if you want to be completely portable:
ps -p 747 -o '%cpu,%mem' | tail -n +2
The cut
command is sort of the column-based equivalent of the simpler row-based commands head
and tail
. (If you really do want to cut columns, it works… but in this case, you probably don't; it's much simpler to pass the -o
params you want to ps in the first place, than to pass extras and try to snip them out.)
Meanwhile, I'm not sure why you think you need to eval something as the argument to echo, when that has the same effect as running it directly, and just makes things more complicated. For example, the following two lines are equivalent:
echo "$(ps -p 747 -o %cpu,%mem)" | cut -c 1-5
ps -p 747 -o %cpu,%mem | cut -c 1-5
Upvotes: 33
Reputation: 172
Use ps --no-headers
:
--no-headers print no header line at all
or use:
ps | tail -n +2
Upvotes: 8
Reputation: 54392
Using awk
:
ps -p 747 -o %cpu,%mem | awk 'NR>1'
Using sed
:
ps -p 747 -o %cpu,%mem | sed 1d
Upvotes: 8
Reputation: 107040
Already picked the winner. Drats...
If you're already using the -o
parameter, you can specify the headings for the particular columns you want to print by putting an equal sign after the name, and the column name. If you put a null string, it'll print no headings:
With standard headings (as you had):
$ ps -p $pid -o%cpu,%mem
%CPU %MEM
0.0 0.0
With custom headings (just to show you how it works):
$ ps -p $pid -o%cpu=FOO,%mem=BAR
FOO BAR
0.0 0.0
With null headings (Notice it doesn't even print a blank line):
$ ps -p $pid -o%cpu="",%mem=""
0.0 0.0
Upvotes: 4