Print next line beside preceding line on column match

Hi,

I have some data like below:

John  254
Chris 254
Matt  123
Abe   123
Raj    487
Moh   487

How can i print it using awk to have:

254 John,Chris
123 Matt,Abe
487 Raj,Moh

Thanks.

Hello james2009,

Could you please try following and let me know if this helps you.

awk '!a[$2]{b[++i]=$2} {a[$2]=a[$2]?a[$2] "," $1:$1} END{for(j=1;j<=i;j++){print b[j],a[b[j]]}}'  Input_file

Thanks,
R. Singh

1 Like

This one compares the current line with the previous line

awk '
function prt() { if (NR>1) print p1, p2 }
{ if ($2!=p2) { prt(); p1=$1; p2=$2 } else { p1=(p1 "," $1) } }
END { prt() }
' inputfile
1 Like

Hi Ravinder, the script is ok. Can you explain the logic pls.

Hello james2009,

Could you please go through the following explanation and let me know if this helps you.

 awk '
!a[$2]{                      ## checking if an array named a whose index is $2 is having NULL value for current second field, if yes then do following.
  b[++i]=$2                  ## create array b element whose index is incrementing by 1 value of variable i and value is current $2.
}
{
  a[$2]=a[$2]?a[$2] "," $1:$1## creating array a with index $2 and concatenating in its own value.
}
END{                         ## END block for awk code now.
  for(j=1;j<=i;j++){         ## starting a for loop from variable j value 1 to till i value.
    print b[j],a[b[j]]       ## printing value of array b whose index is variable j then printing array a value whose index is value of array b whose index is j.
}
}
' Input_file                 ## Mentioning the Input_file here.
 

Thanks,
R. Singh

1 Like