Easy way to add columns from multiple files

If I have several 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 just need the output, for example:

# 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 this is not possible if there are more than 20 files. I also tried using

awk 'NR==FNR{a[NR]=$2;next}{print $1,$2+a[FNR]}' filename1.txt filename2.txt

but it only works with two files and then ignores the rest.

+4
source share
2 answers

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 with 1 for each file, so you can pass all your input files to this awk command.

+5
source

, , paste/awk . , , 2 :

paste * | awk '{ s=$2; for(i=4; i<=NF; i+=2) s+=$i; print $1, s }'

:

1.0 0.1
1.5 1.6
2.0 2.1
2.5 1.5
+1

All Articles