Solution which is works perfect if all headers match from file b

HI Guys,

I have file A.txt

Code:

ID,L1,L2,L3,L4
1A,2a,33a,44b,55c
2A,10a,14a,15b,16c

File B.txt

Code:

ID
L1
L4
L5

Output:-

Code:

ID,L1,L4,L5
1A,55c,n/a
2A,16c,n/a

I have below solution which is works perfect if all header match from file b.

Code:

nawk -v OFS="," '$1=$1' $Lic1 > $Lic2

	nawk '
	BEGIN           {OFS = FS = ","}
	FNR == NR       {h[$0] = NR
                 MX = NR
                 next
                }
	FNR == 1        {for (i=1; i<=NF; i++) if ($i in h) a[h[$i]] = i
                }

                {for (i=1; i<=MX; i++) printf "%s%s", $a, (i==MX)?RS:OFS
                }
	' fileB fileA

Thanks

And the question is?

In nawk you can get a $() error, so you better cast a to a number: $(a+0)

Now it is portable, but you do not want $(0) (the whole line), you want "n/a" .
The following expression does it: (i in a)?$a:"n/a"

Wildly guessing what your request might be, I came up with

awk '
BEGIN           {OFS = FS = ","}
FNR == NR       {h[$0] = NR
                 T[NR] = $0
                 MX = NR
                 next
                }
FNR == 1        {for (i=1; i<=NF; i++) if ($i in h) a[h[$i]] = i
                 for (i=1; i<=MX; i++) printf "%s%s", T, (i==MX)?RS:OFS
                 next
                }

                {for (i=1; i<=MX; i++) printf "%s%s", a?$a:"n/a", (i==MX)?RS:OFS
                }
' fileB fileA

How far would that get you?