Question

I have declared two variables with following content:

$ 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
$ 

I would like to subtract counter values in first variable from counter values in second variable, i.e. the end result needs to look like this:

$ 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
$ 

Integers in second variable are always >= compared to integers in first variable. What is the most elegant method to do this using bash, awk and sed? Should I use bash arrays? I guess I should look towards awk this time? If possible, I would like to avoid static positions and match the counter values with regular expression(" [0-9]+").

Was it helpful?

Solution

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
    }
    '

Note: This will compress multiple adjacent spaces into a single one each.

  • Uses paste to merge the two strings so that corresponding lines follow each other in the single output string.
  • The awk program then parses the pairs of lines and performs the arithmetic; see the source comments.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top