3

I need to transpose/pivot a CSV file. Don't know if that is possible

Suppose this CSV file content:

filename;rating;id;summary
S4348gjO.doc;good;0001;describing how to reach your goals
S4348gjO.doc;good;0002;some recipes for avoiding an argument
S4348gjO.doc;bad;0003;boring part of the page
A234HK.doc;fairly good;0001;how to deploy a server
A234HK.doc;bad;0002;start and stop the server

Output must be:

filename;good;fairly good;bad;id
S4348gjO.doc;describing how to reach your goals; ; ;0001
S4348gjO.doc;some recipes for avoiding an argument; ; ;0002
S4348gjO.doc; ; ;boring part of the page;0003
A234HK.doc; ;how to deploy a server; ;0001
A234HK.doc; ; ;start and stop the server;0002
  • 3
    I don't understand how the input became the output. – Jeff Schaller Aug 20 '16 at 0:33
2

Looks like you want something like:

awk 'BEGIN{FS=OFS=";"}
FNR==1{print "filename;good;fairly good;bad;id"}
$2=="good"{print $1, $4, " ", " ", $3}
$2=="fairly good"{print $1, " ", $4, " ", $3}
$2=="bad"{print $1, " ", " ", $4, $3}' infile

so the corresponding rating column contains the summary and the other two will get just a space (per your example - if you need an empty field replace " " with "")

1

A little modification the don_crissti's script

awk -F\; '
    BEGIN{
        P["good"]="%s;%s;;;%s\n"
        P["fairly good"]="%s;;%s;;%s\n"
        P["bad"]="%s;;;%s;%s\n"
        }                         
    FNR==1{
        print "filename;good;fairly good;bad;id"
        next
        }
    {
        printf(P[$2],$1,$4,$3)
        }
    ' infile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.