rodee
rodee

Reputation: 3151

grep a file and print only n'th word in the line

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

Answers (2)

John1024
John1024

Reputation: 113814

$ awk '/CPU0/{last=$3} END{sub(/[.].*/,"",last); print last}' test
38

How is works

  • /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

zedfoxus
zedfoxus

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:

  • cat will output all lines in test file
  • grep CPU0 will only output those lines that contain CPU0
  • tail -1 will give the last line from grep's output
  • awk will split []# 0-CPU0 38.8%, SM: 1/4, ovl: 62 by space(s)
  • first item is []#, second is 0-CPU0, third is 38.8%
  • awk's printf %d will give you just 38

Upvotes: 4

Related Questions