p.louis p.louis - 5 months ago 12
Bash Question

make math operation from multiple files with shell scripting

I have multiple files, let's say

fname1
contains:

red=5
green=10
yellow=2


fname2
contains:

red=10
green=2
yellow=2


fname3
contains:

red=1
green=7
yellow=4


I want to write script that read from these files, sum the numbers for each colour,
and redirect the sums into new file.

New file contains:

red=16
green=19
yellow=8

Answer

[ awk ] is your friend :

awk 'BEGIN{FS="=";}
            {color[$1]+=$2}
     END{
         for(var in color)
          printf "%s=%s\n",var,color[var]
        }' fname1 fname2 fname3 >result

should do it.

Note

  • If all the filenames start with fname you can even put fname* instead of fname1 fname2 fname3
  • This assumes that there are no blank lines in any file