KB 到 MB 使用 bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19059944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:15:22  来源:igfitidea点击:

KB To MB using bash

bashshell

提问by Lurch

I use a command to get the size of a remote folder, after it's run it returns

我使用命令获取远程文件夹的大小,运行后返回

120928312 http://blah.com

The number is size in bytes. What I'd like to do is have it output in MB, and the httppart removed. I'm guessing greping to a file but not sure how to go about it.

该数字是以字节为单位的大小。我想要做的是以MB为单位输出,并http删除该部分。我猜想访问一个文件,但不知道如何去做。

回答by technosaurus

You can do it with shell builtins

你可以用 shell 内置函数来做到这一点

some_command |while read KB dummy;do echo $((KB/1024))Mb;done

Here is a more useful version:

这是一个更有用的版本:

#!/bin/sh
human_print(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} bytes && break
  KB=$(((B+512)/1024))
  [ $KB -lt 1024 ] && echo ${KB} kilobytes && break
  MB=$(((KB+512)/1024))
  [ $MB -lt 1024 ] && echo ${MB} megabytes && break
  GB=$(((MB+512)/1024))
  [ $GB -lt 1024 ] && echo ${GB} gigabytes && break
  echo $(((GB+512)/1024)) terabytes
done
}

echo 120928312 http://blah.com | human_print

回答by Kent

how about this line:

这行怎么样:

kent$  echo "120928312 http://blah.com"|awk '{/=1024;printf "%.2fMB\n",}'
118094.05MB

回答by Gilles Quenot

Try doing this using bashbuiltins (display an integer like the KB version)

尝试使用bash内置函数执行此操作(显示一个整数,如 KB 版本)

var="120928312 http://blah.com"
echo "$(( ${var%% *} / 1024)) MB"

回答by sw1nn

function bytes_for_humans {
    local -i bytes=;
    if [[ $bytes -lt 1024 ]]; then
        echo "${bytes}B"
    elif [[ $bytes -lt 1048576 ]]; then
        echo "$(( (bytes + 1023)/1024 ))KiB"
    else
        echo "$(( (bytes + 1048575)/1048576 ))MiB"
    fi
}

$ bytes_for_humans 1
1 Bytes
$ bytes_for_humans 1024
1KiB
$ bytes_for_humans 16777216
16MiB

回答by jkshah

Try using awk

尝试使用 awk

awk '{MB=/1024; print $MB}'

$1- value of the first column, size (KB) in this case

$1- 在这种情况下,第一列的值,大小 (KB)