简体   繁体   English

bash awk 轮数

[英]bash awk round number

I want to spit out RAM usage as a percentage of total RAM using top .我想使用top将 RAM 使用量作为总 RAM 的百分比。 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:我有 4gb RAM,因此除以 40.95,所以这个脚本会吐出看起来像这样的东西:

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.我考虑使用bc但我总是收到非法语句错误。 Any ideas how to round it to the 1st decimal place within awk?任何想法如何在awk中将其四舍五入到小数点后一位?

There are a few ways to do that with awk:有几种方法可以用 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.每个都使用输出格式%3.1f来处理舍入。 So all you need to do is add the argument OFMT="%3.1f" to your awk call.所以您需要做的就是将参数OFMT="%3.1f"到您的 awk 调用中。 (Or you may prefer a format of %0.1f The 3 just gives a minimum width; the typical format string rules apply. ) (或者您可能更喜欢%0.1f的格式 3 只给出最小宽度;适用典型的格式字符串规则。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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