Format output in AWK command

hi Friends ,

I have a file as below

s.txt

1~2~~4
2~6~~7
3~8~~9

t.txt

1~2~~4
2~5~8~7
3~8~~7

header for both files is common

header.txt

KEY~DIS~NOT~KAT

to compare 2 files i have used the following code

paste -d '~' s.txt t.txt | awk -F '~' '{c=NF/2;for(i=1;i<=c;i++)if($i!=$(i+c))printf "line %-5s field %s orginal %s changed  %s\n",NR,i-1,$i,$(i+c)}'

I got output as

Actualoutput.txt

line 2     field 1 orginal 6 changed  5
line 2     field 2 orginal  changed  8
line 3     field 3 orginal 9 changed  7

But i am unable to find the solution to make my script inculde the header information in the output file. Plz help me. your help is much appreciated.

ExpectedOutput.txt

KEY~COLUMNNAME~SOURCEVALUE~TARGETVALUE
2  ~ DIS      ~   6       ~    5
2  ~ NOT      ~          ~     8
3  ~ KAT      ~    9     ~     7

Assuming only 1 line in header.txt , try:

awk -F'~' -v header="$(<header.txt)" 'BEGIN{OFS=" ~ ";split(header,h)
print "KEY","COLUMNNAME","SOURCEVALUE","TARGETVALUE"}
FNR==NR{for(i=1;i<=NF;i++) e[FNR,i]=$i;next}
{for(i=1;i<=NF;i++) 
  if($i!=e[FNR,i])
   print FNR,h,e[FNR,i],$i
}' s.txt t.txt

@Elixir . Thanks for the reply. :slight_smile: you made my day. :slight_smile: it is working as Expected.