从其他变量中的整数中减去一个变量中的整数

时间:2014-05-12 15:27:57

标签: bash awk sed

我已声明了两个含有以下内容的变量:

$ echo "$variable1"
Counter values:
out = 323423    in = 7898
counter1    IN= 34    OUT= 232
counter2    IN= 3    OUT= 3
counter555    IN= 2    OUT= 0
counter3    IN= 1232    OUT= 13212
$ echo "$variable2"
Counter values:
out = 323499    in = 7998
counter1    IN= 34    OUT= 238
counter2    IN= 3    OUT= 3
counter555    IN= 2    OUT= 0
counter3    IN= 4248    OUT= 13712
$ 

我想从第二个变量中的计数器值中减去第一个变量中的计数器值,即最终结果需要如下所示:

$ echo "$variable3"
Counter values:
out = 76    in = 100
counter1    IN= 0    OUT= 6
counter2    IN= 0    OUT= 0
counter555    IN= 0    OUT= 0
counter3    IN= 3016    OUT= 500
$ 

第二个变量中的整数始终> =与第一个变量中的整数进行比较。使用bash,awk和sed执行此操作的最优雅方法是什么?我应该使用bash数组吗?我想我这次应该看看awk?如果可能的话,我想避免使用静态位置,并将计数器值与正则表达式(" [0-9]+")匹配。

1 个答案:

答案 0 :(得分:1)

paste -d $'\n' <(printf %s "$variable1") <(printf %s "$variable2") | 
  awk '
    !/= [0-9]/ {getline;print;next}  # pass through lines that contain no numbers
    {
      split($0, refLineFields) # split the 1st line of each pair into fields
      getline                  # read the 2nd line of the pair (into $0)
      for (i=1;i<=NF;++i)      # loop over all fields
          # Replace numerical fields with the difference between
          # their value and the one from the corresponding line,
          # Note that assigning to a field causes the input line to be recomposed
          # so that $0 then contains the _modified_ line.
        if ($i ~ "^[0-9]+$") $i=$i - refLineFields[i]
      # Output the modified line.
      print
    }
    '

注意:这会将多个相邻的空格压缩为一个。

  • 使用paste合并两个字符串,以便相应的行在单个输出字符串中相互跟随。
  • 然后awk程序解析行对并执行算术运算;看到来源评论。