使用脚本提取Ubuntu Sensors命令

时间:2018-10-02 10:15:23

标签: regex bash ubuntu awk

这个问题是Extracting and Processing GPUTemperature Information Using Regexp

的继续

基本上,我想使用传感器命令和脚本(如gawk和bash)提取GPU温度信息。

传感器输出示例如下:

amdgpu-pci-0c00
Adapter: PCI adapter
fan1:        1972 RPM
temp1:        +50.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0600
Adapter: PCI adapter
fan1:        1960 RPM
temp1:        +47.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0200
Adapter: PCI adapter
fan1:        1967 RPM
temp1:        +52.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

pch_skylake-virtual-0
Adapter: Virtual device
temp1:        +33.0°C

amdgpu-pci-0900
Adapter: PCI adapter
fan1:        1893 RPM
temp1:        +51.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0300
Adapter: PCI adapter
fan1:        1992 RPM
temp1:        +53.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Package id 0:  +24.0°C  (high = +80.0°C, crit = +100.0°C)
Core 0:        +23.0°C  (high = +80.0°C, crit = +100.0°C)
Core 1:        +21.0°C  (high = +80.0°C, crit = +100.0°C)

我想根据总线ID的升序打印每个GPU的标签和温度。例如,根据先前的输出,第一个GPUGPU0将是带有标签amdgpu-pci-0200的GPU,GPU1将是amdgpu-pci-0300,直到最后一个GPU4是amdgpu-pci-0c00。这不是coretemp-isa-0000,因为它不是GPU。不管总线ID是连续的还是跳过的,我都希望以升序的方式对其进行标记。

以下bash代码将提取所有GPU温度,而不进行正确的排序。

#!/bin/bash

while [ 1 ]
do
        temp=( $( sensors | IFS=$'\n' gawk 'BEGIN{ RS="\n\n"} { if($0 ~ /amdgpu/) print $0 }' | gawk 'BEGIN{ FS="[+.]" } { if($1 ~ /temp1:/) print $2 }' ))   
        let j=0
        for i in "${temp[@]}"
        do
                echo -en  "GPU $j temp is $i \r "
                j=$(($j +1))
                sleep 1
        done
done

如何解决?

致谢

1 个答案:

答案 0 :(得分:1)

您没有提供实际的预期输出或提供一些有关如何解析输入的详细信息,因此虽然有点猜测,但这可能正是您要查找的内容

$ cat tst.sh
#!/bin/env bash

#while :
#do
    cat file |
    gawk '
        BEGIN { RS="" }
        $1 ~ /amdgpu/ {
            temp = "N/A"
            for (i=1; i<NF; i++) {
                if ($i == "temp1:") {
                    temp = gensub(/^[^0-9]*([0-9]+).*/,"\\1",1,$(i+1))
                }
            }
            temps[$1] = temp
        }
        END {
            PROCINFO["sorted_in"] = "@ind_str_asc"
            for (id in temps) {
                print "GPU" (++cnt), id, temps[id]
            }
        }
    '
    #sleep 1
#done

$ ./tst.sh
GPU1 amdgpu-pci-0200 52
GPU2 amdgpu-pci-0300 53
GPU3 amdgpu-pci-0600 47
GPU4 amdgpu-pci-0900 51
GPU5 amdgpu-pci-0c00 50

只要对此感到满意,只需将cat file更改为sensors并取消注释行即可激活无限循环(假设您有这样做的理由)。

上面使用gensub()和sorted_in使用GNU awk。