简体   繁体   English

如何在bash shell脚本中仅过滤字符串中的数字?

[英]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. 我想测量Raspberry pi 3的温度,并相应地更改文本的背景色。 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. 并在if条件下使用它。 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). 删除文本中不想要的字符的典型工具是trsed (以及使用${var##text}类的结构直接在shell中操作变量,但除非您想使用shell专有的扩展功能,否则这些功能将提供有限的功能)。 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 . 这只是删除( -d )不是( -c )字符类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.]/}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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