3

Objective

On Linux, I am trying to get an end-user friendly string representing available system memory.

Example:

Your computer has 4 GB of memory.

Success criteria

I consider these aspects end-user friendly (you may disagree):

  • 1G is more readable than 1.0G (1 Vs 1.0)

  • 1GB is more readable than 1G (GB Vs G)

  • 1 GB is more readable than 1GB (space-separated unit of measure)

  • memory is more readable than RAM, DDR or DDR3 (no jargon)

Starting point

The free utility from procps-ng has an option intended for humans:

-h, --human
    Show all output fields automatically scaled to shortest three digit unit
    and display the units of print out.  Following units are used.
        B = bytes
        K = kilos
        M = megas
        G = gigas
        T = teras
    If unit is missing, and you have petabyte of RAM or swap, the number is
    in terabytes and columns might not be aligned with header.

so I decided to start there:

> free -h
             total       used       free     shared    buffers     cached
Mem:          3.8G       1.4G       2.4G         0B       159M       841M
-/+ buffers/cache:       472M       3.4G
Swap:         4.9G         0B       3.9G

3.8G sounds promising so all I have to do now is...

Required steps

  • Filter the output for the line containing the human-readable string (i.e. Mem:)

  • Pick out the memory total from the middle of the line (i.e. 3.8G)

  • Parse out the number and unit of measure (i.e. 3.8 and G)

  • Format and display a string more to my liking (e.g. GGB, ...)

My attempt

free -h | \
  awk  '/^Mem:/{print $2}' | \
    perl -ne '/(\d+(?:\.\d+)?)(B|K|M|G|T)/ && printf "%g %sB\n", $1, $2'

outputs:

3.8 GB

Desired solution

  • I'd prefer to just use gawk, but I don't know how

  • Use a better, even canonical if there is one, way to parse a "float" out of a string

  • I don't mind the fastidious matching of "just the recognised magnitude letters" (B|K|M|G|T), even if this would unnecessarily break the match with the introduction of new sizes

  • I use %g to output 4.0 as 4, which is something you may disagree with, depending on how you feel about these comments: https://unix.stackexchange.com/a/70553/10283.

My question, in summary

  • Could you do the above in awk only?
  • Could my perl be written more elegantly than that, keeping the strictness of it?

Remember:

I am a beginner robot. Here to learn. :]

What I learned from Andy Lester

Summarised here for my own benefit: to cement learning, if I can.

for example, this gawk:

echo foo bar baz | awk '{print $2}'

can be written like this in perl:

echo foo bar baz | perl -ane 'print "$F[1]\n";'

Unless there is something equivalent to gawk 's --field-separator, I think I still like gawk better, although of course to do everything in perl is both cleaner and more efficient. (is there an equivalent?)


EDIT: actually, this proves there is, and it's -F just like in gawk:

echo ooxoooxoooo | perl -Fx -ane 'print join "\n", @F'

outputs:

oo
ooo
oooo

  • perl has a -l option, which is just awesome: think of it as Python's str.rstrip (see the link if you are not a Python head) for the validity of $_ but it re-appends the \n to the output automatically for you

Thanks, Andy!


4
  • I say +1 for having an organized question. But you may get better feedback on codereview.stackexchange.com.
    – squiguy
    Mar 30, 2013 at 1:02
  • 1
    Thanks. I was very hesitant to post a "shell one-liner" to a site called Code Review! It felt borderline obsessive.. :) Mar 30, 2013 at 1:09
  • I agree with Stephane. There is no reason for precision to change just because the output happen to fall on an even number.
    – jordanm
    Mar 30, 2013 at 2:16
  • Computer science point of view. Logical, precise. I think my "grandma" would still say 4 GB to a shop attendant rather than 4.0G. At any rate, the question regarding regex remains? Mar 30, 2013 at 2:21

3 Answers 3

3

Yes, I'm sure you could do this awk-only, but I'm a Perl guy so here's how you'd do it Perl-only.

Instead of (B|K|M|G|T) use [BKMGT].

Use Perl's -l to automatically strip newlines from input and add them on output.

I don't see any reason to have Awk do some of the stripping and Perl doing the rest. You can do autosplitting of fields with Perl's -a.

I don't know what the output from free -h is exactly (My free doesn't have an -h option) so I'm guessing at this

free -h | \
perl -alne'/^Mem:/ && ($F[1]=~/(\d+(?:\.\d+)?)[BKMGT]/) && printf( "%g %sB", $1, $2)'
6
  • 1
    Whoa.. I LOVE this answer! Damn! You taught me so much in a one-liner! Awesome!! Thanks! Mar 30, 2013 at 2:41
  • 1
    Glad you like it. Go ahead and accept it, please. This presentation I gave years ago may give you some more tidbits. speakerdeck.com/petdance/a-field-guide-to-the-perl-command-line Mar 30, 2013 at 2:43
  • I absolutely adore your answer, but I am going to wait just a little bit for an awk one, in case it comes. It was my expressed preference. Good to learn some perl from a Master like you though. Will accept in case no awk comes forward.. Mar 30, 2013 at 2:45
  • BTW, Andy, I have noticed the -l switch does not "work" in this one-liner.. free -h | perl -lane '/^Mem:/ && ($F[1] =~ /(\d+(?:\.\d+)?)([BKMGT])/) && printf "%g %sB", $1, $2' Mar 31, 2013 at 1:11
  • 1
    Interesting. The -l will add \n after a print but not after a printf. From the manual perldoc -f print: "Equivalent to print FILEHANDLE sprintf(FORMAT, LIST), except that `$` (the output record separator) is not appended." Mar 31, 2013 at 3:44
2

An awk (actually gawk) solution

free -h | awk 'FNR == 2 {if (match($2,"[BKMGT]$",a)) r=sprintf("%.0f %sB",substr($2,0,RSTART-1), a[0]); else r=$2 " B";print "Your computer has " r " of memory."}'

or broken down for readability

free -h | awk 'FNR == 2 {if (match($2,"[BKMGT]$",a)) r=sprintf("%.0f %sB",
          substr($2,0,RSTART-1), a[0]); else r=$2 " B";
          print "Your computer has " r " of memory."}'

Where

  • FNR is the nth line (if 2 does the {} commands)
  • $2 is the 2nd field
  • if (condition) command; else command;
  • match(string, regex, matches array). Regex says "must end with one of BKMGT"
  • r=sprintf set variable r to sprintf with %.0f for no decimals float
  • RSTART tells where the match occured, a[0] is the first match

Outputs with the exemple above

Your computer has 4 GB of memory.
1
  • Awarding, as it is awk all the way. Andy's solution looks cleaner to me, I would probably remember that more easily, but since it's all awk, the "prize" is yours! ;) Mar 30, 2013 at 19:33
0

Another lengthy Perl answer:

free -b | 
perl -lane 'if(/Mem/){ @u=("B","KB","MB","GB"); $F[2]/=1024, shift @u while ($F[2]>1024); printf("%.2f %s", $F[2],$u[0])}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.