title: How to use bash to split and unknown number of source file names into specified number of output files
body: <p>I am trying to write a script in BASH that will read all the names of files in a source directory, which has an unknown file count, then split those names as evenly as possible between a specified number of output files. User input is source dir, target dir, and target file count.</p>
  
  <p>For example, lets say we have 10 files in a source directory, and the user specifies they want the names of those files to be split between 3 output files.</p>
  
  <p>SOURCE FILE NAMES:</p>
  
  <pre>
  test
  test2
  test3
  test4
  test5
  test6
  test7
  test8
  test9
  </pre>
  
  <p>RESULTING FILES:</p>
  
  <pre>
  FILE1
  test
  test2
  test3
  test4
  </pre>
  
  <p>(has 4)</p>
  
  <pre>
  FILE2
  test5
  test6
  test7
  </pre>
  
  <p>(has 3)</p>
  
  <pre>
  FILE3
  test8
  test9
  test10
  </pre>
  
  <p>(has 3)</p>
  
  <p>So far, I have come up with the below, which will always catch all the files because I'm forcing a 'round up', but wont provide the desired number of output files in all cases as it does not account for an uneven number of file names in an output file.</p>
  
  <pre><code>ls -l -d -1 $source/{*,.*} | tail -n +3 |  awk '{printf "%s\n",$9}' &gt; hdpLoadList
  fileCount=`ls -1 $source | wc -l`
  threadCount=$3 
  
  fptf=$(bc &lt;&lt;&lt; "scale=1;($fileCount/$threadCount)+.9")
  fptf=${fptf:0:1}
  
  sPos=1
  sLen=$fptf
  for i in `seq 1 $threadCount`;
   do
     sed -n ${sPos},${sLen}p hdpLoadList | sed -e ':a;N;$!ba;s/\n/ /g' &gt; hdpLoadP_$i
     sPos=$(($sPos+$fptf))
     sLen=$(($sLen+$fptf))
   done
  </code></pre>