1

I am using the terminal in MAC OS. I want to get on only the total ideal CPU from the top command (just ideal cpu) and stor it to a file.

I have tried this: top | grep -w "CPU usage: " And i got this :

/Test/temp1 » top | grep "CPU usage: "                                                130 ↵
CPU usage: 5.45% user, 11.77% sys, 82.77% idle 
CPU usage: 3.20% user, 3.51% sys, 93.27% idle 
CPU usage: 2.64% user, 2.76% sys, 94.59% idle 
CPU usage: 3.18% user, 2.61% sys, 94.19% idle 

.

I want to store only the last metrics en every line which is "82.77% idle" but without the "% and idel" word, only I want the amount of ideal CPU to store it in a file. Ex:

82.77 
93.27 
94.59 
94.19 

I appreciate your help ,,,

1
  • You could pipe grep's output to sed 's/.*\s\([0-9.]*\)%.*/\1/' Commented May 21, 2019 at 17:48

1 Answer 1

1

You can use a combination of grep and awk to get the required number alone. Here the --line-buffered flag is used, which forces grep to write to the output each time a new line is encountered.

top | grep --line-buffered "CPU usage: " |awk '{ print substr($5, 1, length($5)-1) }'

Or you could directly use awk

top | awk '/^CPU usage: / { print substr($5, 1, length($5)-1) }'
Sign up to request clarification or add additional context in comments.

1 Comment

grep is never needed when you're piping to awk. awk '/CPU usage: / { print substr($5, 1, length($5)-1) }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.