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 ?
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
Using awk
:
ps -p 747 -o %cpu,%mem | awk 'NR>1'
Using sed
:
ps -p 747 -o %cpu,%mem | sed 1d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With