Reputation: 3151
Content of file "test":
[]# 0-CPU4 8.9%, 9336/832, 0x5ffe9b88--0x5ffec000
[]# 0-CPU0 13.5%, aa: 4/3, xvl: 35
[]# 0-CPU1 8.6%, SM: 1/4, ovl: 60
[]# 0-CPU0 38.8%, SM: 1/4, ovl: 62
form this file, I want the percentage of last CPU0, which is 38
(ignoring decimal point)
I use below shell command which works fine, like to know if there is a better way.
grep CPU0 test | tail -1 | awk '/0-CPU0/ {print $3}' | sed 's/\..*//'
#above command prints "38"
Upvotes: 5
Views: 11580
Reputation: 113814
$ awk '/CPU0/{last=$3} END{sub(/[.].*/,"",last); print last}' test
38
/CPU0/{last=$3}
Every time we reach a line that contains CPU0
, we assign the third field to the variable last
.
END{sub(/[.].*/,"",last); print last}
At the end of the file, however many times CPU0
appeared in the file, last
contains the value for the last of the CPU0
lines. The sub
command removes the decimal point and everything after it. Then, we print last
.
Upvotes: 0
Reputation: 37029
Assuming your data was in a file called test:
cat test | grep CPU0 | tail -1 | awk '{ printf("%d", $3) }'
grep CPU0 test | tail -1 | awk '{ printf("%d", $3) }' - condensed
awk ' /CPU0/ {a=$3} END{ printf("%d", a) }' test - more condensed
What it does:
[]# 0-CPU0 38.8%, SM: 1/4, ovl: 62
by space(s)[]#
, second is 0-CPU0, third is 38.8%%d
will give you just 38Upvotes: 4