我想将所有kb,mb,gb,b的值转换为实际字节,例如,“10 kb”应该转换为"10240“字节。
下面是测试函数:
#! /bin/bash
get_value_in_bytes()
{
local value="$1"
local unit_length=0
local number_length=0
local number=0
if [[ "$value" == *"gb" ]]
then
unit_length=2
number_length=$((${#value} - $unit_length))
number=$((${value:0:$number_length})) * 1024 * 1024 * 1024 || -1
elif [[ "$value" == *"mb" ]]
then
unit_length=2
number_length=$((${#value} - $unit_length))
number=$((${value:0:$number_length}))*1024*1024 || -1
elif [[ "$value" == *"kb" ]]
then
unit_length=2
number_length=$((${#value} - $unit_length))
number=$((${value:0:$number_length}))*1024 || -1
elif [[ "$value" == *"b" ]]
then
unit_length=1
number_length=$((${#value} - $unit_length))
number=$((${value:0:$number_length})) || -1
else
number=$((${value:0:$number_length})) || -1
fi
if (( $number < 0 ))
then
echo "error : $value"
else
echo "$number : $value"
fi
}
下面是一个测试:
get_value_in_bytes 10kb
get_value_in_bytes 10mb
get_value_in_bytes 10gb
get_value_in_bytes 10b
get_value_in_bytes 10
get_value_in_bytes not_number_mb
get_value_in_bytes not_number_gb
这是输出:
10*1024 : 10kb
10*1024*1024 : 10mb
./test.sh: line 15: test.sh: command not found
./test.sh: line 15: -1: command not found
0 : 10gb
10 : 10b
0 : 10
0*1024*1024 : not_number_mb
./test.sh: line 15: test.sh: command not found
./test.sh: line 15: -1: command not found
0 : not_number_gb
我希望这个函数可以接受任何值作为输入,如果值不是数字字符串,则将其转换为-1。但是上面的函数并没有像预期的那样工作。
发布于 2022-04-17 14:39:54
下面是一个基于based和case
语句的解决方案:
get_value_in_bytes() {
local bytes=-1
if [[ $1 =~ ^([[:digit:]]+)(b|kb|mb|gb)?$ ]]
then
bytes=${BASH_REMATCH[1]}
case ${BASH_REMATCH[2]} in
kb) bytes=$((bytes * 1024)) ;;
mb) bytes=$((bytes * 1048576)) ;;
gb) bytes=$((bytes * 1073741824)) ;;
esac
fi
printf '%s\n' "$bytes"
}
备注:
bc
.这样的外部工具
b
部门是bit
的。当你指的是byte
.时,你应该使用B
2^10
的单位是KiB
MiB
GiB
等发布于 2022-04-17 16:34:55
作为一个例子,使用Bash的regex并不总是必要的;下面是只使用POSIX-shell语法重写的Fravadona's answer:
#!/usr/bin/env sh
toBytes() {
digits=${1%%[^[:digit:]]*}
unit=${1##*[[:digit:] ]}
case $unit in
kb) bytes=$((digits * 1024)) ;;
mb) bytes=$((digits * 1048576)) ;;
gb) bytes=$((digits * 1073741824)) ;;
b | '') bytes=$((digits)) ;;
*) bytes=-1 ;;
esac
printf '%s\n' "$bytes"
}
for s in 10kb 10mb 10gb 10b 10 not_number_mb not_number_gb; do
toBytes "$s"
done
https://stackoverflow.com/questions/71902566
复制相似问题