I don't think it can get any simpler than the awk
approach, so here's a Perl solution that works for any number of columns, saving each in its own file:
perl -ane 'unless($handles[0]){
for(1..$#F+1){
open(my $fh, ">","file$_");
$handles[$_-1] = $fh
}
}
for my $i (0..$#F){
print { $handles[$i] } "$F[$i]\n"
}' file
Given an input file like this:
$ cat file
foo bar baz bad
foo bar baz bad
foo bar baz bad
foo bar baz bad
foo bar baz bad
foo bar baz bad
The script above will create files file1
through file4
each of which containing the relevant column.
Of course, you can do exactly the same thing in awk
, much more simply and elegantly, but where's the fun in that?
awk '{for(i=1;i<=NF;i++){print $i > "file"i}}' file