Ankit Singh Ankit Singh - 1 year ago 57
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

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:


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

Answer Source

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

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


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

$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 }'

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download