Split File into chunks keeping complete lines in solaris

209 views Asked by At

How can I split a file into 3 with equal (or almost equal) number of lines without breaking a line. for example split a file of 25 lines into 3 files of 9,8 and 8 lines each. I know of split -n l/3 but does not work on Solaris10. Tried some stuff i got online but did not give desired result like:

!/usr/bin/ksh
fspec=~/input.list
num_files=3
total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))
split -l ${lines_per_file} ${fspec} files.
1

There are 1 answers

0
Jotne On BEST ANSWER

Here is a generic solution for you in awk

awk '{a[NR]=$0}  END {t=int (NR/s);r=((NR/s-t)*s);while (n<s) for (i=t*n+++1;i<=t*n;i++) print a[i] > "file"n;while (i++<=NR) print a[i-1] > "file"n}' s=3 infile

This splits the infile to s numbers of file. If you set s=3 you get file1 file2 file3
The data that does not divide up, ends up in last file.


Example

cat number
1       one
2       two
3       three
4       four
5       five
6       six
7       seven
8       eight
9       nine
10      ten

awk '{a[NR]=$0}  END {t=int (NR/s);r=((NR/s-t)*s);while (n<s) for (i=t*n+++1;i<=t*n;i++) print a[i] > "file"n;while (i++<=NR) print a[i-1] > "file"n}' s=3 number

cat file1
1       one
2       two
3       three

cat file2
4       four
5       five
6       six

cat file3
7       seven
8       eight
9       nine
10      ten