【问题标题】:Regular expression in bash with awk带有awk的bash中的正则表达式
【发布时间】:2021-02-19 21:50:50
【问题描述】:
我正在尝试从 bash 中的 lm 传感器获取我的 AMD GPU 温度。
所以我通过管道 awk 得到正确的线路。但是现在我需要一个正则表达式来从中获取数据。
我当前的代码是:
sensors | awk '/edge/ {print$2}'
这会输出 +53.0°C
现在我只需要 53.0.如何在 bash 中做到这一点?
【问题讨论】:
标签:
bash
ubuntu
awk
lm-sensors
【解决方案1】:
请您尝试关注一下。
awk 'match($2,/[0-9]+(\.[0-9]+)?/){print substr($2,RSTART,RLENGTH)}' Input_file
或
sensors | awk 'match($2,/[0-9]+(\.[0-9]+)?/){print substr($2,RSTART,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,RSTART,RLENGTH) ##printing sub string from 2nd field whose starting point is RSTART till RLENGTH.
}
' Input_file ##Mentioning Input_file name here.
【解决方案2】:
无需任何正则表达式,您可以在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}'