awk打印除以1024的shell脚本

时间:2014-08-01 10:03:35

标签: bash shell awk

我正在尝试对awk输出过程进行一些arthimatic操作。 我的示例文件包含字符串和它的计数。现在我试图使计数值的格式为MB(defualt count将以字节为单位。)

示例:        myfile.txt的

   a 123455
   b 34455566
   c 10394934839
   d 102445555

我的剧本:

  cat myfile.txt | while read line; do name=$line ; name=`echo $fname|awk '{print   $1}'` ; cnt=`echo $fname|awk '{print $1}'`; if [$cnt -gt 1024] ; then echo "$name value in critical $cnt";fi done

问题:我想将cnt值转换为MB(cnt / 1024/1024)。

不知道如何实现这一目标。

5 个答案:

答案 0 :(得分:5)

您可以直接在awk中进行操作,而无需在BASH中进行循环:

awk '{print $1, $2/(1024*1024)}' file
a 0.117736
b 32.8594
c 9913.38
d 97.6997

OR用于2位小数输出:

awk '{printf "%s %.2f\n", $1, $2/(1024*1024)}' file
a 0.12
b 32.86
c 9913.38
d 97.70

答案 1 :(得分:2)

你可以这样做(纯粹的Bash):

$ cat myfile.txt | while read l f ; do echo $l $((f/1024/1024)) ;if [ $((f/1024/1024)) -gt 
1024 ] ; then echo "$l value in critical ";fi done
a 0
b 32
c 9913
c value in critical 
d 97

答案 2 :(得分:1)

kent$  awk '{printf "%s %.2f\n",$1,$2/1024/1024}' file
a 0.12
b 32.86
c 9913.38
d 97.70

更改%.2f以获得不同的精度。

如果您想添加关键检查:

awk '{v=$2/1024/1024;printf "%s %.2f%s\n",$1,v,(v>1024?" <=critical":"")}' file
a 0.12
b 32.86
c 9913.38 <=critical
d 97.70

答案 3 :(得分:0)

另一种方式

awk '{$2/=2^20}1' file

格式化

awk '$2=sprintf("%.2f",$2/2^20)' file

有暴击

awk '$2=sprintf("%.2f%s",x=($2/2^20),x>1024?" [critical]":"")' test

答案 4 :(得分:0)

如果您有结构化数据并且想要每行循环,只需使用awk即可。除了节省CPU周期(在大多数情况下可以忽略不计)之外,最大的好处是避免了Bash奇怪的引用和空间呻吟。

awk '{ MB = int($2/1024/1024); print $1 " " MB; if (MB > 1024) print $1 " value in critical"}' myfile.txt

输出:

a 0
b 32
c 9913
c value in critical
d 97

打破它:

MB = int($2/1024/1024)    ->    Take the value in the second field ($2).
                                Make it into an integer (to round the number)
                                and store it in the variable MB.

print $1 " " MB           ->    Print the first field ($1), followed by
                                a space, and finally the value in MB.

if (MB > 1024)
    print $1 " val.."     ->    If MB < 1024, print first field followed by msg.