Dan
Dan

Reputation: 951

Print only first three numbers from string

I'm trying to print out the memory total in GB but print only the first three digits. I've tried using cut and sed without luck.

#!/bin/bash
echo MemoryTotal $(( $(cat /proc/meminfo | grep MemTotal | awk '{ print $2 }') / 1024 ))

Yields:

MemoryTotal 257669GB

But I'd like this to print out:

MemoryTotal 257GB

Upvotes: 0

Views: 244

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

With sed + numfmt tools:

sed '1 s/ \(.\)B$/\U\1/;q' /proc/meminfo | numfmt --field 2 --from=auto --to=iec

Sample output (from my current OS):

MemTotal:            2.2G

Upvotes: 0

blhsing
blhsing

Reputation: 106901

Since /proc/meminfo outputs memory size in KB and you want the output in GB, what you should do instead is to divide the number in KB by 1024 * 1024.

echo MemoryTotal $(( $(grep MemTotal /proc/meminfo | awk '{ print $2 }') / 1024 / 1024))GB

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158100

Use free -g:

free -g | awk 'NR==2{print $2}'

Upvotes: 4

Related Questions