Shell script: copying columns by header in a csv file to another csv file -


i have csv file i'll using input format looking this:

xvalue,value1-avg,value1-median,value2-avg,value3-avg,value3-median
1,3,4,20,14,20

the key attributes of input file each "value" have variable number of statistics, statistic type , "value" separated "-". want output statistics of "values" separate csv files.

the output this:

value1.csv

xvalue,value1-avg,value1-median
1,3,4

value2.csv

xvalue,value2-avg
1,20

i've tried finding solutions this, can find ways copy column number, not header name. need able use header names append associated statistics each of output csv files.

any appreciated!

p.s. output file may have been written during previous runs of script, meaning code should append output file

untested should close:

awk -f, ' nr==1 {     (i=2;i<=nf;i++) {         outfile = $i         sub(/-.*/,".csv",outfile)         outfiles[i] = outfile     } } {     delete(outstr)     (i=2;i<=nf;i++) {         outfile = outfiles[i]         outstr[outfile] = outstr[outfile] fs $i     }     (outfile in outstr)         print $1 outstr[outfile] >> outfile } ' infile.csv 

note deleting whole array delete(outstr) gawk-specific. other awks can use split("",outstr) same effect.

note appends output wanted existing files means you'll header line repeated on every execution. if that's issue, tell how know when generate header line or not solution think you'll want this:

awk -f, ' nr==1 {     (i=2;i<=nf;i++) {         outfile = $i         sub(/-.*/,".csv",outfile)         outfiles[i] = outfile     }     (outfile in outfiles) {         exists[outfile] = ( ((getline tmp < outfile) > 0) && (tmp != "") )         close(outfile)     } } {     delete(outstr)     (i=2;i<=nf;i++) {         outfile = outfiles[i]         outstr[outfile] = outstr[outfile] fs $i     }     (outfile in outstr)         if ( (nr > 1) || !exists[outfile] )             print $1 outstr[outfile] >> outfile } ' infile.csv 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -