Hat
Hat

Reputation: 1731

bash awk round number

I want to spit out RAM usage as a percentage of total RAM using top. The script I have so far is

top -l 1 |
awk '/PhysMem/ {
    print "RAM\nwired:" $2/40.95 "% active:" $4/40.95 "% inactive:" $6/40.95 "% free:" $10/40.95 "%"
}'

I have 4gb RAM, hence divide by 40.95, so this script spits out something that looks like:

RAM
wired:16.1172% active:46.2759% inactive:8.79121% free:28.8156%

I only want it to show the percentages to 1 place past the decimal and I'm not sure how to do this. I looked into using bc but I always get an illegal statement error. Any ideas how to round it to the 1st decimal place within awk?

Upvotes: 1

Views: 10323

Answers (1)

William Pursell
William Pursell

Reputation: 212248

There are a few ways to do that with awk:

... | awk '{ print $2/40.95 }' OFMT="%3.1f"

... | awk '{ printf( "%3.1f\n", $2/40.95 )}'

each use the output format %3.1f to handle rounding. So all you need to do is add the argument OFMT="%3.1f" to your awk call. (Or you may prefer a format of %0.1f The 3 just gives a minimum width; the typical format string rules apply. )

Upvotes: 5

Related Questions