How do I append the occurrence of a field using awk? How do I append the occurrence of a field using awk? shell shell

How do I append the occurrence of a field using awk?


Awk solution:

awk 'BEGIN{ FS=OFS="," }{ $0=$0 OFS (++a[$1]) }1' file

The output:

John,Guitar,1John,Vocals,2John,Piano,3Paul,Bass,1Paul,Vocals,2George,Guitar,1George,Vocals,2Ringo,Drums,1

The same with print operator:

awk 'BEGIN{ FS=OFS="," }{ print $0,(++a[$1]) }' file


With awk:

awk 'BEGIN{FS=OFS=","} {print $1,$2,++counter[$1]}' file

Output:

John,Guitar,1John,Vocals,2John,Piano,3Paul,Bass,1Paul,Vocals,2George,Guitar,1George,Vocals,2Ringo,Drums,1


Another way with awk

awk '{b=$0;sub(",.*","");$0=b","++c[$0]}1' infile