2

I would like to cut 150.8 from this string temp1: +150.8°F (crit = +197.6°F). Here is my script for logging temperatures with the command sensors:

#!/bin/bash
now=$(date +"%m_%d_%Y")    # get current date
now_excel=$(date +"%D %H:%M")    # get current date & time in excel format

file_dir="/var/www/html/logs"
file="$file_dir/logging_$now.csv"    # backup name and directory

temp=$(sensors -Af | sed -n '2{p;q}')    # temp1:       +150.8°F  (crit = +197.6°F)
#temp_num="$temp" | sed 's/+\(.*\)°/\1/g'

# add line to csv
printf "$now_excel" >> "$file"
printf ", " >> "$file"
printf "$temp" >> "$file"
printf "\n" >> "$file"

find "$file_dir"/* -mtime +3 -exec rm {} \;    # remove any backup files older than 3 days

exit 0
2

Using sed

Here is one way:

$ sensors -Af | sed -n '2{s/°.*//; s/[^+-]*//; p; q}'
+105.8

Or, using the same command inside command substitution to capture its output in a variable:

temp=$(sensors -Af | sed -n '2{s/°.*//; s/[^+-]*//; p; q}')

s/°.*// removes the first occurrence of the degree symbol, °, and everything after it. s/[^+-]*// removes everything up to but not including the first + or -.

Using awk

$ sensors -Af | awk 'NR==2{print $3+0; exit;}'
105.8

The number that we want is in the third field. Because the third field contains characters, for example +105.8°F, we add 0 to it. This forces awk to convert it to what we want: a number.

4
  • 2
    Assuming (pretty safely) that the temperature is above zero. – Jeff Schaller Jul 20 '16 at 19:56
  • 2
    @JeffSchaller Ha! For those working in the arctic, the answer is now updated to allow for negative temperatures. – John1024 Jul 20 '16 at 20:01
  • 1
    +1. the sed version should use [FC] instead of just F. most of the world uses celsius/centigrade rather than fahrenheit. – cas Jul 21 '16 at 7:07
  • @cas Good point. I updated to eliminate F and C. – John1024 Jul 22 '16 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.