Transpose column to row

Hi i have a file which has values seperated by "," as shown below and I want to transpose for every doc_id in one row.

Input:

DOC_ID,KEYWORD
105,REGISTROS
105,GEOLOGIA
105,NUCLEOS
105,EXPEDIENTE
105,PROGRAMAS
10025,EXPEDIENTE
10025,LOCALIZACIONES
10025,OFICIOS
10025,PROGRAMAS
10025,REPORTES
10065,EXPEDIENTE
10065,LOCALIZACIONES
10065,OFICIOS
10065,PLANOS
10065,PROGRAMAS
10065,REPARACIONES
10065,PRODUCCION

Outout:

DOC_ID TRANSPONSE_KEYWORD
105 REGISTROS,GEOLOGIA,NUCLEOS,EXPEDIENTE,PROGRAMAS
10025 EXPEDIENTE,LOCALIZACIONES,OFICIOS,PROGRAMAS,REPORTES
10065 EXPEDIENTE,LOCALIZACIONES,OFICIOS,PLANOS,PROGRAMAS,REPARACIONES,PRODUCCION
 

Thanks for your help in advance

awk -F, 'NR>1{a[$1]=a[$1]?a[$1]","$2:$2}END{print "DOC_ID TRANSPONSE_KEYWORD";for (i in a){print i" "a}}' file
1 Like
awk -F, 'END{for(i in a) print a}NR==1{print $1 OFS "TRANSPOSED_"$2;next}{a[$1]=a[$1]?a[$1] FS $2:$1 OFS $2}' file
1 Like

Another aproach:

perl -n -e 'chomp;@b=split(/,/);if ($last ne $b[0]) {print  "\n".$b[0]." " }else{print ","};$last=$b[0];print $b[1] ' file
1 Like

Looks input file has been sorted. If not, sort it first. :slight_smile:

awk -F , '!a[$1]++ {printf RS $1 OFS $2 ;next}{printf FS $2}' infile

If not ask for space between first and second column, the code can be more shorter.

awk -F , '!a[$1]++ {printf RS $1}{printf FS $2}' infile 
1 Like