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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With