Shell脚本乘以行并添加总和

时间:2014-05-27 02:29:36

标签: shell

 Thanks all for the inputs but now i landed up in another problem .

  This is my Orginal syntax 

   db2 list tablespaces show detail | grep -e " Free pages" -e " Page size"
   Free pages                           = Not applicable
 Page size (bytes)                    = 4096
 Free pages                           = Not applicable
    Page size (bytes)                    = 4096
  Free pages                           = Not applicable
  Page size (bytes)                    = 4096
   Free pages                           = 36960
    Page size (bytes)                    = 32768
  Free pages                           = 40800
 Page size (bytes)                    = 16384
  Free pages                           = 22656
   Page size (bytes)                    = 4096
  Free pages                           = Not applicable
      Page size (bytes)                    = 4096

      Now if i see Not applicable then i should remove Not applicable line and as well as the proceeding line for that i used the below syntax 

  db2 list tablespaces show detail | grep -e " Free pages" -e " Page size"  | awk '/Not/{getline;next} 1'

  Free pages                           = 36960
 Page size (bytes)                    = 32768
 Free pages                           = 40800
  Page size (bytes)                    = 16384
 Free pages                           = 22656
 Page size (bytes)                    = 4096

但是我不确定为什么最后的4096会在输出中出现?

然后我需要删除(字节)并只打印值,所以我使用下面的语法

 db2 list tablespaces show detail | grep -e " Free pages" -e " Page size"  | awk '/Not/{getline;next} 1' | sed 's/(bytes)//g' | awk '{print$4}'

36960  32768 40800 16384 22656  4096

我忘了提到关于我的第一个帖子(我的问题是我想将第1行乘以第2行,然后第3行到第4行,第5行到第6行,直到输出结束为止最后添加全部总和)

in the second line , fourth line and sixth line i need to take only the first 2 charchater and then multiply

如下所示

36960 * 32  40800 * 16   然后继续  从那里我需要GB中的值再除以1024和1024,因为原始值是KB

                 I know i am asking too much but can some one help ??
                     Waiting for some reply .. Thanks

1 个答案:

答案 0 :(得分:1)

对于bash shell script

#!/bin/bash
TOTAL=0
while read A && read B; do
    (( TOTAL += A * B ))"
done
echo "Total: $(( TOTAL / 1024 / 1024 )) GB"

然后运行:

bash script.sh < input_file

如果您希望它可以在多种类型的shell中使用,那么该概念应该易于转换。只需考虑命令bc和其他类似工具。