使用 awk 提取 gcc 版本

Using awk to extract gcc version

我想用awk命令获取gcc版本,但是返回的字符串是空的

$ gcc --version
gcc (GCC) 11.1.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc --version | head -1 | awk '{for(i=1;i<=NF;i++){ if(match($i,/^[0-9]\.[0-9]\.[0-9]$/))  {print $i; exit 0}}}'
$

不知道为什么会失败。有什么想法吗?

您只检查一位数。

只要允许多位数字就可以了,就像这样:

awk '{for(i=1;i<=NF;i++){ if(match($i,/^[0-9]{1,2}\.[0-9]*\.[0-9]*$/))  {print $i; exit 0}}}'

gcc 还有一个短版本选项:

-dumpversion

所以你不需要 awk :)

gcc --version |  awk '{ print $NF;exit }'

输出(在我的系统上):

$ gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ gcc --version |  awk '{ print $NF;exit }'
9.3.0
$

或:

gcc -dumpspecs | grep -A1 version | tail -1
gcc -dumpfullversion

输出:

9.3.0