Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to add columns from multiple files

Tags:

bash

awk

paste

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.

like image 823
Izaak Williamson Avatar asked Feb 11 '23 12:02

Izaak Williamson


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

like image 81
anubhava Avatar answered Feb 23 '23 12:02

anubhava