awk not giving the output expected

Hello,

I am practising awk and decided to compare two columns and print the result of the comparison as third column

i/p data

c1,c2,c3
1,a,b
1,b,b

i am trying to compare the last two columns and if they match I am trying to print match else mismatch (Ideally i want that as a last column in the same file

#!/bin/bash
IFS="," while read -r $line
a=awk '{print $1, ($NF=$(NF-1))?"match":"mismatch"}'<filename.txt
awk -v var=$a '{BEGIN s=a}{print $0,s}
'

expected output

c1,c2,c3,c4
1,a,b,mismatch
1,b,b,match

but all I am getting is

c1,c2,c3
1,a,b
1,b,b

or if just say awk'{print $NF}
I am getting the output as

c1,c2,c3
1,a,b
1,b,b

same out put even if i use $(NF-1)

I also tried commenting the
awk -v var=$a '{BEGIN s=a}{print $0,s} line in my code and ran it

#!/bin/bash
IFS="," while read -r $line
awk '{print $1, ($NF=$(NF-1))?"match":"mismatch"}'<filename.txt
#awk -v var=$a '{BEGIN s=a}{print $0,s}
'

the output i get is

c1,c2,c3,match
1,a,b,match
1,b,b,match

But i Read $NF returns the last column and NF-1 returns the last but one column.

Please advice where my thinking is wrong.

Thanks.

You're taking the scenic route, running multiple awk multiple unneeded times. On top:

  • You're reading a line (from where? terminal, I presume?) to no avail - the variable is not used anywhere any more.
  • You're assigning a variable a to no avail innthe first awk .
  • You're using that a variable as a constant, independent of the condition you want applied, in the second awk .
  • You're using the assignment operator = in lieu of the comparison operator == .
  • You're not giving awk the right field separator , .

Try instead:

awk -F, '{print $0, NR==1?"c4":($2!=$3?"mis":"")"match"}' OFS=, file
c1,c2,c3,c4
1,a,b,mismatch
1,b,b,match
1 Like

Hi try something like this:

awk '{print $0, ($NF==$(NF-1))?"match":"mismatch"}' FS=, OFS=, filename.txt

what's the meaning of : after "c4" in the above code written does this represent start of if condition also
-- ignore this i understood that you are checking if its the first line then add a field called c4 else compare the two columns and print the result in the end.

inside the if condition
($2!=$3?"mis":"")"match" i have only two possibilities match and mismatch so would i be wrong to write
($2!=$3?"mismatch":"match")

thank-you

------ Post updated at 08:59 PM ------

Yes it works but this code wont add a field to my file and print the values in it I have used the code mentioned by RUDIC and this iworks

#!/bin/bash
awk -F, '{print $0, NR==1?"c4":($NF==$(NF-1))?"match":"mismatch"}' OFS=,

Ideone.com - oarShB - Online Bash Interpreter & Debugging Tool

No. Using ($2!=$3?"mis":"")"match" is just me being lazy avoiding typing in "match" twice when it's printed anyhow, in either case.

In fact, it does. Unfortunately, it adds "mismatch" in lieu of "c4" to the header line.

Okay i will once again look at it thanks