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.
Asked
Active
Viewed 2.5k times
24

phuclv
- 37,963
- 15
- 156
- 475

javanoob17
- 243
- 1
- 3
- 10
4 Answers
44
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

John1024
- 109,961
- 14
- 137
- 171
-
2How would i go about doing it in GB – javanoob17 Apr 23 '15 at 01:56
-
1For Debian based users, this may not work - If so, try replacing the `**` with `^`, or replace `1024**2` with the result: `1048576` – Addison Oct 13 '19 at 07:15
-
1@Addison Interesting. It works fine for me under Debian with GNU awk but not under `mawk`. I checked and `^` is [POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/) while `**` is not. So, for greatest compatibility, I updated the answer, as per your suggestion, to use `^`. Thanks. – John1024 Oct 13 '19 at 19:00
3
You can use the numfmt
tool
$ cat /proc/meminfo | numfmt --field 2 --from-unit=Ki --to-unit=Mi | sed 's/ kB/M/g'
MemTotal: 128692M
MemFree: 17759M
MemAvailable: 119792M
Buffers: 9724M
...
$ cat /proc/meminfo | numfmt --field 2 --from-unit=Ki --to=iec | sed 's/ kB//g'
MemTotal: 126G
MemFree: 18G
MemAvailable: 118G
Buffers: 9.5G
...
$ cat /proc/meminfo | numfmt --field 2 --from-unit=Ki --to-unit=Gi | sed 's/ kB/G/g'
MemTotal: 126G
MemFree: 18G
MemAvailable: 117G
Buffers: 10G
...

phuclv
- 37,963
- 15
- 156
- 475
1
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

PotatoFarmer
- 2,755
- 2
- 16
- 26
-
instead of setting then unset the variable you just need to use `local` – phuclv Jan 21 '23 at 05:01
-
`local` is not available in POSIX, its a Bash feature/[bash-ism](https://betterprogramming.pub/24-bashism-to-avoid-for-posix-compliant-shell-scripts-8e7c09e0f49a). POSIX-compliant particularly helpful for barebones shells found in embedded devices. – PotatoFarmer Jan 22 '23 at 06:04
0
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.