bash awk 轮数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14881684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash awk round number
提问by Hat
I want to spit out RAM usage as a percentage of total RAM using top. The script I have so far is
我想使用top. 我到目前为止的脚本是
top -l 1 |
awk '/PhysMem/ {
print "RAM\nwired:" /40.95 "% active:" /40.95 "% inactive:" /40.95 "% free:" /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 bcbut I always get an illegal statement error. Any ideas how to round it to the 1st decimal place within awk?
我只希望它显示小数点后一位的百分比,我不知道如何做到这一点。我考虑过使用,bc但我总是收到非法语句错误。任何想法如何将其四舍五入到 awk 中的小数点后一位?
回答by William Pursell
There are a few ways to do that with awk:
有几种方法可以用 awk 做到这一点:
... | awk '{ print /40.95 }' OFMT="%3.1f"
... | awk '{ printf( "%3.1f\n", /40.95 )}'
each use the output format %3.1fto 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.1fThe 3 just gives a minimum width; the typical format string rules apply. )
每个都使用输出格式%3.1f来处理舍入。所以你需要做的就是将参数添加OFMT="%3.1f"到你的 awk 调用中。(或者您可能更喜欢%0.1fThe 3的格式只给出最小宽度;适用典型的格式字符串规则。)

