I have several files which look like
file1.dat:
1 1
1 3 4
5 9 10 11
file2.dat:
3 0
8 9 0
3 9 2 4
typically with many more rows (with each row containing one less column than the previous row). I devised a hybrid bash/awk script to sum the rows of each file, e.g. using the above as an example:
out.dat:
4 1
9 12 4
8 18 12 15
The script works as expected but is quite slow. Well over 30 minutes for 100 files each with 10000 rows on my machine. The script seems to spend most of the time collecting the nth row from all the files. Is there a way to perform my operation simply by passing file*.dat
to the awk command (see below)?
#!/bin/bash
ROWS=$1; shift
OUT_FILE=$1; shift
IN_FILE=("$@")
for i in `seq 1 1 ${ROWS}`; do
# Get ith row from all input files
for j in "${IN_FILE[@]}"; do
tail -n+${i} ${j} | head -1 >> "temp.dat"
done
# Sum the rows
awk '{for (j=1;j<=NF;j++) a[j]+=$j} END {for (j in a) printf a[j] " "}' temp.dat >> ${OUT_FILE}
echo >> ${OUT_FILE}
rm temp.dat
done
Script usage based on the above example: ./RowSums.sh 3 out.dat file*.dat
9 12 0
? Shouldn't it be9 12 4
? Do all files have the same number of rows?9 12 4
. And yes the dimensions of all the files are equal.