Reputation: 651
I have a file with 30 columns ( repeated ID Name and Place) and I need to extract 3 columns at time and put them into a new file every-time :
ID Name Place ID Name Place ID Name Place ID Name place ...
19 john NY 23 Key NY 22 Tom Ny 24 Jeff NY....
20 Jen NY 22 Jill NY 22 Ki LA 34 Jack Roh ....
So I will have 10 files like these -
Output1.txt
ID Name Place
19 john NY
20 Jen NY
Output2.txt
ID Name Place
23 Key NY
22 Jill NY
and 8 more files like these. I can print columns like
awk '{print $1,$2,$3}' Input.txt > Output1.txt
but it may be too cumbersome for 10 files. Is there anyway I can make it faster?
Thanks!
Upvotes: 1
Views: 54
Reputation: 37404
$ awk '{for(i=0;i<=NF/3-1;i++) print $(i*3+1), $(i*3+2), $(i*3+3)>i+1".txt"}' file
$ cat 1.txt
ID Name Place
19 john NY
20 Jen NY
Upvotes: 1
Reputation: 85663
Tweaking a bit from this wonderful Ed Morton's answer,
awk -v d=3 '{sfx=0; for(i=1;i<=NF;i+=d) {str=fs=""; for(j=i;j<i+d;j++) \
{str = str fs $j; fs=" "}; print str > ("output_file_" ++sfx)} }' file
will do the split-up of files as you requested.
Remember the awk
variable d
defines the number of columns to split-upon which is 3 in your case.
Upvotes: 3
Reputation: 10865
$ awk '{for (i=1;i<=NF;i+=3) {print $i,$(i+1),$(i+2) > ("output" ((i+2)/3) ".txt")}}' file.txt
# output1.txt
ID Name Place
19 john NY
20 Jen NY
# output2.txt
ID Name Place
23 Key NY
22 Jill NY
# output3.txt
ID Name Place
22 Tom Ny
22 Ki LA
# output4.txt
ID Name place
24 Jeff NY
34 Jack Roh
Upvotes: 3