当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - shell script for awk print divide value with 1024

问题描述:

I am trying to do some arthimatic operations on awk output process.

my sample file contains string and it's count. Now i am trying to make the count values to be in format of MB (defualt count will come in bytes.)

Example :

myfile.txt

 a 123455

b 34455566

c 10394934839

d 102445555

my script :

 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

Problem: I want the cnt value should be convert into MB ( cnt/1024/1024) .

no clue how to achieve this.

网友答案:

You can do it like this (pure 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
网友答案:

You can do it directly in awk without looping in BASH:

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

OR for 2 decimal point output:

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

change the %.2f to gain different precision.

if you want to add the critical check:

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
网友答案:

Another awk way

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

Formatted

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

With crit

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

When you have structured data and you want to loop per line, just use awk. Besides the saving of CPU cycles (which is negligible in most cases) the biggest benefit is that you avoid the weird quote and space moaning of Bash.

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

Output:

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

Breaking it down:

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.
分享给朋友:
您可能感兴趣的文章:
随机阅读: