我需要解析comand的输出,并将数字转换为千字节(如果不是的话)。
来自系统的输出:
5.1g Service
227292 Xorg
218284 gnome-shell使用我正在使用的命令不可能获得相同类型的所有结果(Kilboytes)。我需要检查来自Service的数据是否以GB或千字节为单位,并进行转换。
剧本:
#!/bin/bash
#Variables
comand=`top -b -o RES -n 1 | awk '{print $6,$NF}'| grep $1`
#Regex
regexGB="([0-9]+)(\.([0-9]+))*g"
regexKB="([0-9]+(?:\.[0-9]+)?)"
regexdigit=".*[0-9]"
if [[ $comand =~ $regexGB ]];then
echo "Digit is in GB"
echo "${BASH_REMATCH[*]}"
i=1
n=${#BASH_REMATCH[*]}
while [[ $i -lt $n ]]
do
echo " capture[$i]: ${BASH_REMATCH[$i]}"
let i++
done
elif [[ $comand =~ $regexKB ]];then
echo "Digit is in KB"
else
echo "Printing Output $1. Comand: $comand"
fi结果:
Digit is in GB
5.1g 5 .1 1
capture[1]: 5
capture[2]: .1
capture[3]: 1我试着将${BASH_REMATCH$i * 1024相乘,但它不起作用。我怎样才能把千兆字节的数字转换成千字节呢?
发布于 2022-06-30 12:24:20
您可以使用bash 过程替代避免两次读取命令输出。复合if可以捕获需要计算的输出,并(可能)转换为be。使用bash参数展开和模式匹配从千兆字节输出中移除尾随的'g‘,然后转换为千字节。
#!/bin/bash
re_gb="([0-9]+)(\.([0-9]+))g"
re_kb="([0-9]+)"
while read -r line ; do
if [[ $line =~ $re_gb || $line =~ $re_kb ]] ; then
if [[ ${BASH_REMATCH[0]} == *g ]] ; then
# remove the trailing 'g' from the gigabytes regex capture group
num=${BASH_REMATCH[0]//g/}i
# use bc for converting to kilobytes as
# bash cannot perform multiplication on floats.
# Dividing by one removes the float.
# Remove the divide by one for decimal output.
bc <<<"$num * 1024 * 1024 / 1"
else
echo "${BASH_REMATCH[0]}"
fi
fi
done < <(top -b -o RES -n 1 | awk '{print $6,$NF}'| grep $1)使用命令中的输出示例:
5.1g Service
227292 Xorg
218284 gnome-shell脚本输出将是:
$ ./script
5347737
227292218284
https://stackoverflow.com/questions/72813931
复制相似问题