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?
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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.