Ankit Singh Ankit Singh - 5 months ago 8
Linux Question

Is there a command to output only part of a command result in Linux?

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?

Answer

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).