我想將所有帶有 kb,mb,gb,b 的值轉換為實際位元組,例如,“10kb”應該轉換為“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。但是上面的功能并沒有按預期作業。
uj5u.com熱心網友回復:
這是一個基于 bash ERE 和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"
}
評論:
Shell 算術只能處理整數。對于浮點計算,您必須使用外部工具,例如
bc.單位
b為.bit你應該B在你的意思時使用byte。旁白:基于的單位
2^10是KiBMiBGiB等......
uj5u.com熱心網友回復:
作為一個說明,使用 Bash 的正則運算式并不總是必要的;這是僅使用 POSIX-shell 語法重寫的Fravadona 的答案:
#!/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://www.uj5u.com/net/459787.html
