If pattern in column 3 matches pattern in column 2 (any row), print value in column 1

Hi all,

I have searched and searched, but I have not found a solution that quite fits what I am trying to do.

I have a long list of data in three columns. Below is a sample:

1,10,8
2,12,10
3,13,12
4,14,14
5,15,16
6,16,18

What I need to do is as follows: If a number in column three matches a number in column two, print "," and the number in the corresponding row in column one. If there is no match, just print ",". So an expected result for the sample would be as follows:

1,10,8,
2,12,10,1
3,13,12,2
4,14,14,4
5,15,16,6
6,16,18,

I've assumed that AWK would be the best tool for this task, but I am open to using any tool. The solutions I have found and tried only match corresponding rows. They don't match a pattern in one column to any pattern in another column. I'm guessing a loop may be required, but I am a novice to looping.

The values in column one are just the ordinal numbers for the rows, if that is relevant to a solution.

I am very grateful for any help. Thank you.

Suppose that column 3 matches both a previous row and another row further down. What happens?

a bit of a "shot in the dark - different results as I believe the description doesn't jive with the sample data.
awk -f bleed.awk myFile where bleed.awk is:

BEGIN {
  FS=OFS=","
}
{
   t2[$2]=$1
   t3[$3]=$1
   t3t[$1]=$3
}
END {
  for (i in t2)
    print t2, i, t3t[t2], (i in t3)?t3:""
}

results in:

1,10,8,2
2,12,10,3
3,13,12,
4,14,14,4
5,15,16,
6,16,18,5
1 Like

Thank you so much, vgersh99! I believe that solution will work!

actually (I think) it should be - depending on how "strict" your definition/goal is - pick your poison :

BEGIN {
  FS=OFS=","
}
{
   t2[$2]=$1
   t3[$3]=$1
   t3t[$1]=$3
}
END {
  for (i in t2)
    print t2, i, t3t[t2], (i in t3)?t3:( t3t[t2] in t2)?t2[t3t[t2]]:""
}

resulting in:

1,10,8,2
2,12,10,3
3,13,12,2
4,14,14,4
5,15,16,6
6,16,18,5