2

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?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
JimmyD
  • 2,629
  • 4
  • 29
  • 58
  • 1
    if you show the input line, perhaps you could use `grep -oP` too.. see https://stackoverflow.com/questions/10358547/how-to-grep-for-contents-after-pattern for example – Sundeep Nov 07 '20 at 11:13

2 Answers2

2

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}'
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93