简体   繁体   English

将数字转换为千兆字节(sed,awk,sh,bash)

[英]Convert number to gigabytes (sed, awk, sh, bash)

I have the following multi-line output: 我有以下多行输出:

Volume Name: GATE02-SYSTEM
Size: 151934468096
Volume Name: GATE02-S
Size: 2000112582656

Is it possible to convert strings like: 是否可以像这样转换字符串:

Volume Name: GATE02-SYSTEM
Size: 141.5 Gb
Volume Name: GATE02-S
Size: 1862.75 Gb

with sed/awk? 与sed / awk? I looked for answers for the only number output like: 我为唯一的数字输出寻找答案,例如:

echo "151934468096" | awk '{ byte =$1 /1024/1024**2 ; print byte " GB" }'

but can't figure out how to apply it to my case. 但无法弄清楚如何将其应用于我的案子。

EDIT: I'd like to clarify my case. 编辑:我想澄清我的情况。 I have the following one-liner: 我有以下一线:

esxcfg-info | grep -A 17 "\\==+Vm FileSystem" | grep -B 15 "[I]s Accessible.*true" | grep -B 4 -A 11 "Head Extent.*ATA.*$" | sed -r 's/[.]{2,}/: /g;s/^ {12}//g;s/\|----//g' | egrep -i "([V]olume Name|^[S]ize:)"

which generates output above. 上面产生输出。 I want to know what to add more after the last command to get the desired output. 我想知道在最后一个命令之后添加更多内容以获得所需的输出。

printf "Volume Name: GATE02-SYSTEM\nSize: 151934468096\nVolume Name: GATE02-S\nSize: 2000112582656" |
awk '/^Size: / { $2 = $2/1024/1024**2 " Gb" }1'

Using (GNU) sed and bc : 使用(GNU) sedbc

... | sed 's@Size: \([0-9]*\)@printf "Size: %s" $(echo "scale = 2; \1 / 1024 ^ 3" | bc)GiB@e'
             ^^^^  ^^^^^^^^^^ ^^^^^^                    ^^^^^^^^^  ^^ ^^^^^^^^^^    ^^     ^
               1        2        3                          4       5      6         7     8
  1. Matching Size: lines. 匹配Size:线。
  2. Capturing the number of bytes (potentially vulnerable if empty or zero, strengthen for production use) 捕获字节数(如果为空或为零,则很容易受到攻击,请加强以供生产使用)
  3. Replacing with printf output 替换为printf输出
  4. scale = sets the number of decimals for bc scale =设置bc的小数位数
  5. Using the sed capture group (number of bytes) 使用sed捕获组(字节数)
  6. The mathematical operation on the byte number 字节数的数学运算
  7. Piping all that to bc for evaluation 将所有内容发送给bc进行评估
  8. Telling sed to execute the "replace" part of the s statement in a subshell. 告诉sed在子外壳中执行s语句的“替换”部分。

Another option is numfmt (where available, since GNU coreutils 8.21): 另一个选择numfmt (自GNU coreutils 8.21起可用):

... | sed 's@Size: \([0-9]*\)@printf "%s" $(echo \1 | numfmt --to=iec-i --suffix=B)@e'

This doesn't give you control over the decimals, but "works" for all sizes (ie gives TiB where the number is big enough, and does not truncate to "0.00 GiB" for too-small numbers). 这不能让您控制小数,但是可以对所有大小进行“操作”(即,给TiB提供足够大的数字,而对于太小的数字则不能截断为“ 0.00 GiB”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM