Two columns-Common records - 20 files

Hi Friends,

I have an input file like this

cat input1
x 1
y 2
z 3
a 2
b 4
c 6
d 9
cat input2
x 7
h 8
k 9
l  5
m 9
d 12
c 7

Similarly I have 20 files, but now I want to match on column1, and print the corresponding values as 20 different columns

cat output
x 1 7 ..................................value_in_file20
d 9 12.................................value_in_file20
c 6 7...................................value_in_file20

with 245 posts (most of which were awk-related)... what have you tried so far?

awk 'NR==FNR{a[$1]=$0;next}$1 in a{print a[$1],$0}' *.txt

And instead of seeing 21 columns, I see only 3.

Thanks for testing my awk skillset. I like this way. :slight_smile:

awk -f jac.awk file1 file2 ... fileN
jac.awk:

FNR==1 {argc=(argc)?argc+1:2}
{v[$1];a[argc,$1]=$2}
END {
  for( i in v) {
    printf i
    for(j=2;j<=argc;j++) {
      idx=j SUBSEP i
      printf("%c%s",OFS,(idx in a)?a[idx]:OFS)
    }
    printf ORS
  }
}

Thanks a ton.

If I understood it right, it prints all common records if col1 is present in two or more files. And if there is no value even if col1 is present in only two files, it would print 0 instead.

Did I get it right?

that's correct - I just changed the code print ''empty string' if a particular value is not present in col1 of a particular file. Not sure how you wanted it: 0 or 'empty field.

1 Like