0

I've written the shell command below to output the CPU's clock speed as an integer:

grep -m 1 'cpu MHz' /proc/cpuinfo | grep -o -E '[0-9]+'

OUTPUT:

900
063

This is because the exact clock speed is 900.063. Essentially, I want the command to return the 900 part but not the part after the decimal (.063).

Any help is much appreciated, thanks.

1
  • Is appending | head -n 1 on the end not acceptable? This will give you the first line of output. Commented Mar 17, 2020 at 2:24

7 Answers 7

3

This might be easier done in awk:

awk -F: '/cpu MHz/ {print int($2); exit}' /proc/cpuinfo
  • -F: - split on :
  • /cpu MHz/ on lines matching cpu MHz, do:
    • {print int($2); exit}' - convert second field to integer, print it and exit (so we get only the first match)
1
  • Or GNU awk -F[:.] '/cpu MHz/{print $2; exit} Commented Mar 17, 2020 at 17:52
0

There are many possibilities. Here's another one:

grep -m 1 'cpu MHz' /proc/cpuinfo | cut -f2 -d: | cut -f1 -d.
0

Below is Try

command

sed -n '/cpu MHz/s/.*://p' /proc/cpuinfo | sed "s/\..*//g"

Awk method

awk  -F ":" '/cpu MHz/{gsub(/\..*/,"",$NF);print $NF}' /proc/cpuinfo

python

#!/usr/bin/python
import re
k=re.compile(r'cpu MHz')
m=open('/proc/cpuinfo','r')
for i in m:
    if re.search(k,i):
        print i.split(":")[-1].split(".")[0]
0

Using sed is

grep -m 1 'cpu MHz' /proc/cpuinfo | sed -r 's/^(.*? )([0-9]+)(\..+)$/\2/g'
0

With grep:

grep -om1 'cpu MHz[^.]*' /proc/cpuinfo | grep -o '[[:digit:]]*'

Get the line without the dot and the following characters, then grep for the digits.

If your grep supports Perl-compatible regular expressions (PCRE):

grep -oPm1 'cpu MHz.* \K[[:digit:]]+' /proc/cpuinfo

Everything before the \K is matched as usual, but not included in the output (variable length lookbehind).

0

Adding some anchor (like the leading space) should give you what you need:

$ grep -m 1 '^cpu MHz' /proc/cpuinfo | grep -oE ' [0-9]+'
 900

If the leading space on the output is a problem, you can anchor on the dot:

$ grep -m 1 '^cpu MHz' /proc/cpuinfo | grep -oE '[0-9]+\.'
900.

If both space and dot are a problem, we need to step up to a higher level regex, PCRE:

$ grep -oPm 1  '^cpu MHz.* \K[0-9]+(?=\.)' /proc/cpuinfo
900

Which checks both the space and dot, but prints neither.

An equivalent with sed may be:

$ sed -nE 's/^cpu MHz.* ([0-9]+)\..*$/\1/p;T;q' /proc/cpuinfo
900

And with awk:

$ awk -F '[ .]' '/^cpu MHz/{print $3;exit}' /proc/cpuinfo
900
0

avg:

awk '/cpu MHz/{SUM+=$NF; LINE+=+1}END {printf "%0d" ,SUM/LINE}' /proc/cpuinfo

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.