3

I have a large tab-delimited text file which contains a header and data. I want to split the file into smaller files by column, with the header excluded, and the files named as the column name.

pos    red    green    blue
123    0|0    1|0      0|0
321    1|0    1|0      0|0
231    0|0    0|0      0|0
213    0|0    1|0      1|0

and I need to split the files into:

pos.txt:
123
321
231
213

red.txt:
0|0
1|0
0|0
0|0

green.txt:
1|0
1|0
0|0
1|0

blue.txt:
0|0
0|0
0|0
1|0

I tried:

awk 'NR==1{h=$0; next}
!seen[$3]++{f=${h[$3]}".txt"; print >> f}' infile

but it hasn't been working...

  • Do you know for certain that the entire file is four columns of data? – DopeGhoti May 12 '16 at 21:53
  • Can there ever be space(s) in a field value (or a header value)? – G-Man Says 'Reinstate Monica' May 13 '16 at 3:36
3

You could try like this:

awk 'NR==1{for (i=1;i<=NF;i++) a[i]=$i; next}
{for (i=1;i<=NF;i++) {print $i > a[i]".txt"}}' infile

On header line this saves the value of each field in an array then for the rest of the lines it prints each field to the corresponding filename.

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.