If I have multiple files like this:
filename1.txt
# 0.2
1.0 0.0
1.5 1.0
2.0 0.8
2.5 1.1
filename2.txt
# 0.5
1.0 0.1
1.5 0.6
2.0 1.3
2.5 0.4
where all of their first columns are the same. I simply want an output like:
# 0.7
1.0 0.1
1.5 1.6
2.0 2.1
2.5 1.5
I know that
paste filename1.txt filename2.txt | awk '{print $1, $2+$4}'
works but it is unfeasible when there are over 20 files. I have also tried using
awk 'NR==FNR{a[NR]=$2;next}{print $1,$2+a[FNR]}' filename1.txt filename2.txt
but it only works with 2 files then seems to ignore the rest.
You can use this awk
:
awk '{a[FNR]=$1; s[FNR]+=$2} END{for (i=1; i<=FNR; i++) print a[i], s[i]}' file1 file2
# 0.7
1.0 0.1
1.5 1.6
2.0 2.1
2.5 1.5
FNR
starts from 1 for each file so you can pass all of your input files to this awk command.
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