问题描述
我正在尝试通过bash中的lm传感器获取我的AMD GPU温度。 所以我用awk传递了正确的行。但是现在我需要一个正则表达式来从中获取数据。
我当前的代码是:
sensors | awk '/edge/ {print$2}'
这将输出+ 53.0°C
现在我只需要53.0。如何在bash中执行此操作?
解决方法
没有任何正则表达式,您可以在awk
中进行此操作:
# prints 2nd field from input
awk '{print $2}' <<< 'edge +53.0°C foo bar'
+53.0°C
# converts 2nd field to numeric and prints it
awk '{print $2+0}' <<< 'edge +53.0°C foo bar'
53
# converts 2nd field to float with one decimal point and prints it
awk '{printf "%.1f\n",$2+0}' <<< 'edge +53.0°C foo bar'
53.0
因此,您可以使用:
sensors | awk '/edge/ {printf "%.1f\n",$2+0}'
,
请您尝试以下。
awk 'match($2,/[0-9]+(\.[0-9]+)?/){print substr($2,RSTART,RLENGTH)}' Input_file
OR
sensors | awk 'match($2,RLENGTH)}'
说明: 添加以上详细说明。
awk ' ##Starting awk porgram from here.
match($2,/[0-9]+(\.[0-9]+)?/){ ##using match function to match digits DOT digits(optional) in 2nd field.
print substr($2,RLENGTH) ##printing sub string from 2nd field whose starting point is RSTART till RLENGTH.
}
' Input_file ##Mentioning Input_file name here.