gawk -F, ' NR == 1 { print "Name," $0 } NR > 1 { for ( i = 1; i <= NF; i++ ) { if ( $i ) T[$i] R[$i FS i] } } END { n = asorti(T) for ( i = 1; i <= n; i++ ) { for ( j = 1; j <= NF; j++ ) { if ( ( T[i] FS j ) in R ) S = S ? S FS 1 : T[i] FS 1 else S = S ? S FS 0 : T[i] FS 0 } print S S = "" } } ' file