根据bash中第二列的匹配来增加列

时间:2018-11-13 14:06:40

标签: bash shell scripting multiple-columns text-processing

我有两个文件。第一个文件具有特定cpu类型的计算机总数。它有两列。这就是它的样子。

  5 custom
  3 n1-highcpu-32
  3 n1-highcpu-4
 11 n1-highmem-16
 17 n1-standard-1
  9 n1-standard-16
 27 n1-standard-2
 13 n1-standard-4
  5 n1-standard-8

第二个文件具有每种CPU类型的每月成本。它具有以下格式:

n1-standard-1   25
n1-standard-2   49
n1-standard-4   97
n1-standard-8   194
n1-standard-16  388
n1-standard-32  777
n1-standard-64  1553
n1-highmem-2    60
n1-highmem-4    121
n1-highmem-8    242
n1-highmem-16   484
n1-highcpu-4    72
n1-highcpu-32   580
custom      53

要计算总体有效成本,我需要从第一个文件的第二列中获取每个变量,并将其乘以第二个文件中的相应价格。

一旦做到这一点,我们需要将单个价格相加得出总成本。

2 个答案:

答案 0 :(得分:2)

awk 'FNR==NR{cost[$1]=$2;next}{sum=$1*cost[$2];print $2,sum;total+=sum}END{print total}' file2 file1

答案 1 :(得分:1)

使用Perl Oneliner

> cat santhu1
  5 custom
  3 n1-highcpu-32
  3 n1-highcpu-4
 11 n1-highmem-16
 17 n1-standard-1
  9 n1-standard-16
 27 n1-standard-2
 13 n1-standard-4
  5 n1-standard-8
> cat santhu2
n1-standard-1   25
n1-standard-2   49
n1-standard-4   97
n1-standard-8   194
n1-standard-16  388
n1-standard-32  777
n1-standard-64  1553
n1-highmem-2    60
n1-highmem-4    121
n1-highmem-8    242
n1-highmem-16   484
n1-highcpu-4    72
n1-highcpu-32   580
custom      53
> perl -lane 'BEGIN {%kv=map split(/\s+/),qx(cat santhu2)} { print $F[0]*$kv{$F[1]}," ",$F[1] }' santhu1
265 custom
1740 n1-highcpu-32
216 n1-highcpu-4
5324 n1-highmem-16
425 n1-standard-1
3492 n1-standard-16
1323 n1-standard-2
1261 n1-standard-4
970 n1-standard-8
>