Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract columns from different files with awk

Tags:

awk

I have two folders A1 and A2. The names and the number of files are same in these two folders. Each file has 15 columns. Column 6 of each file in folder 'A1' needs to substrate from the column 6 of each file in folder 'A2'. I would like to print column 2 and 6(after subtraction) from each file to a folder A3 with the same filenames. How can I do this with awk?

f1.txt file in folder A1

RAM     AA   159.03  113.3  122.9  34.78    116.3 
RAM     BB   151.24   70    122.9  142.78   66.4
RAM     CC   156.70   80    86.2   70.1     54.8


  f1.txt file in folder A2    

RAM     AA   110.05  113    122.9    34.78    116.3
RAM     BB   150.15  70     122.9    140.60   69.4 
RAM     CC   154.70  89.2   86.2     72.1     55.8


desired output

AA   0
BB  2.18
CC  -2
like image 920
user1588971 Avatar asked Aug 10 '12 02:08

user1588971


2 Answers

Try this:

paste {A1,A2}/f1.txt | awk '{print $2,$6-$13}'

In bash: {A1,A2}/f1.txt will expand to A1/f1.txt A2/f1.txt (It's just a shortcut. Never mind.)
I use paste command to merge files vertically.
The awk command is quite simple here.

like image 58
kev Avatar answered Sep 22 '22 20:09

kev


One way using awk:

awk 'FNR==NR { array[$1]=$2; next } { if ($1 in array) print $1, array[$1] - $2 > "A3/f1.txt" }' ~/A1/f1.txt ~/A2/f1.txt

FIRST EDIT:

Assuming an equal number of files in both directories (A1 and A2) with filenames paired in the way you describe:

for i in A1/*; do awk -v FILE=A3/${i/A1\//} 'FNR==NR { array[$1]=$2; next } { if ($1 in array) print $1, array[$1] - $2 > FILE }' A1/${i/A1\//} A2/${i/A1\//}; done

You will need to create the directory A3 first, or you'll get an error.

SECOND EDIT:

awk 'FNR==NR { array[$2]=$6; next } { if ($2 in array) print $2, array[$2] - $6 > "A3/f1.txt" }' ~/A1/f1.txt ~/A2/f1.txt

THIRD EDIT:

for i in A1/*; do awk -v FILE=A3/${i/A1\//} 'FNR==NR { array[$2]=$6; next } { if ($2 in array) print $2, array[$2] - $6 > FILE }' A1/${i/A1\//} A2/${i/A1\//}; done
like image 24
Steve Avatar answered Sep 21 '22 20:09

Steve