javanoob17
javanoob17

Reputation: 293

How to display /proc/meminfo in Megabytes?

I want to thank you for helping me my related issue. I know if I do a cat /proc/meminfo it will only display in kB. How can I display in MB? I really want to use cat or awk for this please.

Upvotes: 29

Views: 31199

Answers (4)

phuclv
phuclv

Reputation: 41962

You can use the numfmt tool

$ cat /proc/meminfo | numfmt --field 2 --from-unit=Ki --to-unit=Mi --format "%'.2f" | sed 's/ kB/M/g'
MemTotal:      128,670.55M
MemFree:       14,076.93M
MemAvailable:  77,498.78M
Buffers:        3,034.75M
...
$ </proc/meminfo numfmt --field 2 --from-unit=Ki --to=iec | sed 's/ kB//g'
MemTotal:            126G
MemFree:             18G
MemAvailable:        118G
Buffers:            9.5G
...
$ </proc/meminfo sed 's/ kB//g' | numfmt --field 2 --from-unit=Ki --to-unit=Gi --format "%'.1f"
MemTotal:           125.7
MemFree:            13.8
MemAvailable:       75.7
Buffers:             3.0
...

Upvotes: 7

PotatoFarmer
PotatoFarmer

Reputation: 2984

Putting together John1024's answer and tips from shane's answer into function:

if [ -f "/proc/meminfo" ]; then
  meminfo () {
    __meminfo=$(awk '$3=="kB"{if ($2>1024^2){$2=$2/1024^2;$3="GB";} else if ($2>1024){$2=$2/1024;$3="MB";}} 1' /proc/meminfo)
    echo "$__meminfo" | column -t;
    unset __meminfo;
  }
  HW_TOTALRAM=$(meminfo | awk '/MemTotal/ {printf "%.2f", $2; print $3}')
fi

meminfo function result

Upvotes: 1

shane
shane

Reputation: 171

A single line bash entry for storing a memory quantity in MBs. This is for MemTotal but works for others like MemFree.

MEM_TOTAL_MB=`awk '/MemTotal/ {printf( "%d\n", $2 / 1024 )}' /proc/meminfo`

Notes:

backtick (`) and single quote (') are used.

replace %d with %.2f if you want to display as a float with 2 decimal level precision.

Upvotes: 0

John1024
John1024

Reputation: 113934

This will convert any kB lines to MB:

awk '$3=="kB"{$2=$2/1024;$3="MB"} 1' /proc/meminfo | column -t

This version converts to gigabytes:

awk '$3=="kB"{$2=$2/1024^2;$3="GB";} 1' /proc/meminfo | column -t

For completeness, this will convert to MB or GB as appropriate:

awk '$3=="kB"{if ($2>1024^2){$2=$2/1024^2;$3="GB";} else if ($2>1024){$2=$2/1024;$3="MB";}} 1' /proc/meminfo | column -t

Upvotes: 48

Related Questions