有没有办法通过一个Bash命令将1K
等字符串转换为1000
,1M
到1000000
等?我想避免成为一百万和三十一个人为此创建一个> 10行或> 100个字符的单行黑客。类似于iso2int 5MB
。
修改:units -t '5MB' 'bytes
有效,但该工具不可用。有没有简单的方法来转换 5M
或5MB
并且类似于字节?
max的解决方案很优雅,但在我的情况下最短的等价物至少是sed -e 's/b//i;s/k/*1000/i;s/m/*1000000/i;s/g/*1000000000/i;s/t/*1000000000000/i' | bc
。
答案 0 :(得分:3)
这样的东西?
$ echo "1K + 10M" | sed -e "s/K/*1024/g;s/M/*1024*1024/" | bc
10486784
编辑:
sed -e 's/t/kg/i;s/g/km/i;s/m/kk/i;s/k/*1000/ig;s/b//i' | bc
答案 1 :(得分:1)
修改强>
我的原始答案只是 愚蠢 。这是一个基于max taldykin's sed
/bc
excellent answer的纯Bash解决方案。
s=21TB;(( $BASH_VERSINFO >= 4 ))&&s=${s^^};s=${s/B};s=${s/E/KP};s=${s/P/KT}; s=${s/T/KG};s=${s/G/KM};s=${s/M/KK};s=${s//K/*1024};printf "%'u\n" $((s))
这比我原来的单行程更长,因为它包含不区分大小写的事实,而后者没有(尽管它可以和功能一样)。当调整为等效功能时,字符数只是max的两倍。
<强>原始强>
这是一个纯粹的Bash解决方案:
作为一项功能(见下面的单行代码):
#!/bin/bash
# written by Dennis Williamson 2010-12-09
# for https://stackoverflow.com/questions/4399475/unformat-disk-size-strings
expandsi () {
# set k to 1000 if that's your preference, p is a pattern to match unit chars
local k=1024 p='E|P|T|G|M|K| ' # exa, peta, tera, giga, mega, kilo, bytes
local b=$1 c e s=${p//|} # s is the list of units
(( $BASH_VERSINFO >= 4 )) && b=${b^^} # toupper for case insensitivity
b=${b%B*} # strip any trailing B from the input
c=${b: -1} # get the unit character
c=${c/%!($p)/ } # add a space if there's no unit char
b=${b%@($p)*} # remove the unit character
e=${s#*${c:0:1}} # index into the list of units
# do the math, remove the single quote to omit the thousands separator
printf "%'u\n" $((b * k**${#e}))
}
测试功能:
testvals='1 22 333 4444 '
testvals+='4B 44B 1000B '
testvals+='1M 1MB 987MB '
testvals+='1K 23KB 1KB 100K '
testvals+='10G 10GB 3333G '
testvals+='3T 12PB '
# exabytes is pushing it for Bash's int capacity
# on my system, printf "%'u\n" -1 gives 18,446,744,073,709,551,615
testvals+='15EB '
for i in $testvals
do
expandsi $i
done
结果:
1
22
333
4,444
4
44
1,000
1,048,576
1,048,576
1,034,944,512
1,024
23,552
1,024
102,400
10,737,418,240
10,737,418,240
3,578,781,499,392
3,298,534,883,328
13,510,798,882,111,488
17,293,822,569,102,704,640
正如所承诺的那样,最终,单行版本:
$ b=200GB k=1024 p='E|P|T|G|M|K| ';s=${p//|} b=${b%B*};c=${b: -1};c=${c/%!($p)/ };b=${b%@($p)*};e=${s#*${c:0:1}};printf "%'u\n" $((b * k**${#e}))
214,748,364,800