简体   繁体   中英

Regular expression in bash with awk

I'm trying to get my AMD GPU temperature from lm-sensors within bash. So I piped awk to get the correct line. But now I need a regular expression to get the data from it.

My current code is:

sensors | awk '/edge/ {print$2}'

This outputs +53.0°C

Now I only need the 53.0. How can I do this in bash?

Without any regex, you can do this in 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

So for your case, you can use:

sensors | awk '/edge/ {printf "%.1f\n", $2+0}'

Could you please try following.

awk 'match($2,/[0-9]+(\.[0-9]+)?/){print substr($2,RSTART,RLENGTH)}' Input_file

OR

sensors | awk 'match($2,/[0-9]+(\.[0-9]+)?/){print substr($2,RSTART,RLENGTH)}'

Explanation: Adding detailed explanation for above.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM