Reputation: 113
Say I have 2 data files dat1.txt
1 1
2 2
And dat2.txt
2 2
3 3
How can I use awk to "average" these files and save this to a new file? So in this case I want output of a file dat3.txt:
1.5 1.5
2.5 2.5
Upvotes: 1
Views: 90
Reputation: 37394
$ awk '{a[FNR]+=$1; b[FNR]+=$2}END{for(;++i<=FNR;) print a[i]/(ARGC-1), b[i]/(ARGC-1)}' f1 f2
1.5 1.5
2.5 2.5
Explained:
{
a[FNR]+=$1 # sum col values into arrays
b[FNR]+=$2 # array for each field
}
END {
for(;++i<=FNR;) # iterate arrays in ascending order
print a[i]/(ARGC-1), b[i]/(ARGC-1) # and print array contents divided by filecount
}
Upvotes: 0
Reputation: 195039
This awk one-liner should work:
awk '{n=NF/2;for(i=1;i<=n;i++)
printf "%.1f%s",($i+$(n+i))/2,i==n?RS:FS}' <(paste f1 f2)
Upvotes: 2
Reputation: 10039
awk '{for(i=1;i<=NF;i++)Sum[FNR"-"i]+=$i}
END {
for(l=1;l<=NR;l++){
for(i=1;i<=NF;i++) printf( "%2.1f ", Sum[l"-"i]/NR)
printf( "\n")
}
}' dat.1 dat.2
Assuming both file have the same number of line and argument
Upvotes: 0
Reputation: 16997
Try, this supports more than two files too, you can input files like myfiles*.txt
Input
$ cat f1.txt
1 1
2 2
$ cat f2.txt
2 2
3 3
Script
awk '
FNR==1{
nf++
nc = NF
}
{
for (i=1; i <= NF; i++)
s[FNR,i] += $i;
if (FNR > mnr) mnr = FNR
}
END {
for (i = 1; i <= mnr; i++)
{
for (c=1; c <= nc; c++)
printf("%s%f", (c>1?OFS:""), s[i,c]/nf);
printf "\n"
}
}
' f1.txt f2.txt # you can also input f*.txt
Output
1.500000 1.500000
2.500000 2.500000
Upvotes: 0