简体   繁体   中英

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?

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. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM