user898082
user898082

Reputation:

Formatting numbers with shell

I have this Script:

var=$(cat /proc/meminfo | grep MemFree | sed 's/[^0-9]//g')
echo "$(($var / 1024)) MB / 12.288 MB Memory free\n"

it outputs something like this:

10887 MB / 12.288 MB Memory free

But for better readability I want the first number to be like this 10.887 I tried numfmt, but for some reasons it's not included in my destro or coreutils.

EDIT: because of some misconceptions: this is european formatting so we separate with "." and decimal digits are initiated with ","

Upvotes: 1

Views: 129

Answers (2)

anubhava
anubhava

Reputation: 785266

You can replace your code with awk:

awk '/MemTotal/{m=$2/(1024*1024)}
     /MemFree/{printf "%.3f GB / %.3f GB Memory free\n", $2/(1024*1024), m}' /proc/meminfo
1.721 GB / 3.675 GB Memory free

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 80941

printf (and friends) can do it with the (according to the man page) SUSv2 format flag '.

So this should do what you want if your locale is set correctly.

memfree=$(sed -ne '/MemFree/{s/[^0-9]//g;p}' /proc/meminfo)
printf "%'d MB / 12.288 MB Memory free\n" "$((memfree / 1024))"

Upvotes: 0

Related Questions