简体   繁体   中英

How to filter only digits from a string in bash shell scripting?

I want to measure temperature of Raspberry pi 3, and change the background color of the text accordingly. As the code goes, we can print the temperature on the display. Now, I want to filter the digits only out of the text. And use that in the if condition. The source code goes like this:

#!/bin/bash

measurement()
{
    i=1
    echo "Reading Temperature"
    echo "Updating time is set to $1"
    while [ $i -eq 1 ]; do
        temp="$(vcgencmd measure_temp | cut -d= -f 2 | cut -d\' -f 1)"
            tput setaf 7

        if [[ $temp -ge 70 ]]; then
                    tput setab 1
                    echo -ne "Temperature = $temp\r"
        elif [[ $temp -ge 65 && $temp -le 69 ]]; then
                    put setab 3
                    echo -ne "Temperature = $temp\r"
        elif [[ $temp -ge 60  && $temp -le 64 ]]; then
                    tput setab 2
                    echo -ne "Temperature = $temp\r"
        elif [[ $temp -ge 55 && $temp -le 59 ]]; then
                        tput setab 6
                        echo -ne "Temperature = $temp\r"
        else
            tput setab 4
            echo -ne "Temperature = $temp\r"
        fi
        sleep $1
        done
}

if [ -n "$1" ]; then
        sleep_time=$1
        measurement $sleep_time
else
        read -p "Enter the Update Time: " sleep_time
        measurement  $sleep_time
fi

enter image description here

The typical tools for removing unwanted characters from text are tr and sed (and manipulating variables directly in the shell, with constructs like ${var##text} , but unless you want to use shell specific extensions those provide limited capability). For your use case, it seems easiest to do:

temp="$(vcgencmd measure_temp | tr -cd '[[:digit:]]')"

This simply deletes ( -d ) all characters that are not ( -c ) a member of the character class digit .

You could use a builtin string operation to print just the digits and periods in a variable. The following is a global substring replacement of any character that is not a digit or period with an empty string:

echo "${temp//[^0-9.]/}"

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