Specify the file that you want to split (fname) and the number of files (nfiles) that you want to split it into and this script does the calculations to determine how lines go into each file and then does the split:
#!/bin/sh
nfiles=5
fname="somefile"
totlines="$(wc "$fname" | awk '{print $1}')"
lines_per_file=$(( (totlines+nfiles-1)/nfiles ))
lines_per_file=$(( lines_per_file + lines_per_file % 2 ))
[ $((lines_per_file*(nfiles-1)+2 )) -gt $totlines ] && { echo Failed ; exit 1 ; }
split -l "$lines_per_file" "$fname"
Note that, mathematically, with a single invocation of split
, not all combinations of parameters admit a solution. As an example, suppose fname has 50 lines and you want to split
it into 12 files each with an even number of lines. There is no possible solution. At 4 lines per file, split
would need 13 files. At 6 lines per file, split
would need only 9 files.