2

My question is, when we type a command with grep in terminal we get output along with the title:

For example:

lscpu | grep MHz 

Will output:

CPU MHz: 1216.851 

But what if I only want:

1216.851 

As the output? Is there any other command to perform this task?

1
  • 1
    In addition to awk, also see cut and sed. Commented Jan 24, 2016 at 8:01

1 Answer 1

6

While there are other ways, the most straightforward would probably be awk:

$ lscpu | grep MHz | awk '{print $3}' 2494.038 

Or:

$ lscpu | grep MHz | awk '{print $NF}' 2494.038 

$3 represents the third field in the output (separated by any amount of whitespace). $NF represents the LAST field in the output, no matter how many fields there are.

You can also skip grep entirely and just do it all with awk:

$ lscpu | awk '/MHz/ { print $NF; exit }' 2494.038 

As @glenn jackman pointed out, GNU grep can also do this:

lscpu | grep --color=never -oP 'MHz:\s+\K.*' 

But the other examples above are POSIX-friendly (although systems that have lscpu probably also have GNU grep).

Sign up to request clarification or add additional context in comments.

1 Comment

Or, if you have GNU grep and you like PCRE regexes: lscpu | grep -oP 'MHz:\s+\K.*'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.