efficient way to parse vmstat output

4.4k views Asked by At

I'm trying to efficiently parse vmstat output preferably in awk or sed, it also should work on both linux and hp-ux. For example I would like to cut cpu idle % ("92" in this case) from the following output:

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
11  0 385372 101696  61704 650716    0    1     5     9    6   12  5  2 92  0

unfortunately the vmstat output can differ on different linux distributions and hp-ux, also columns can vary in length and can be presented in other order.

I tried to write some nice awk oneliner, but eventually ended with python solution:

$ vmstat | python -c 'import sys; print dict(zip(*map(str.split, sys.stdin)[-2:])).get("id")'
92

Do you know better way to parse mentioned output, to get number values of desired column name?

2

There are 2 answers

0
Michał Šrajer On BEST ANSWER

using awk you can do:

vmstat | awk '(NR==2){for(i=1;i<=NF;i++)if($i=="id"){getline; print $i}}'

This should get value of "id" column on Linux as well as on HP-UX or any other standard unix system.

Tested on Linux, HP-UX and Solaris.

0
user5075558 On
$ vmstat | python -c 'import sys; print sys.stdin.readlines()[-1].split()[-2]'
95