Categories

File splitter update

I said last time that I wanted to make the file splitter function a bit more sophisticated. I would like to be able to wrap the distribution so it goes file 1,2,3,3,2,1,1,2..  etc

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034

function split-file {
[CmdletBinding()]
param (
  [string]$file="data.txt",
  [string[]]$outfiles,
  [switch]$wrap
) 

 if (!(Test-Path $file)){throw "File $file not found"}
 
## delete previous files
 $num = $outfiles.count
 foreach ($ofile in $outfiles) {
  if (Test-Path $ofile){Remove-Item $ofile}
 }
 
 $list = @()
 if ($wrap) {
    0..$($num-1) | foreach { $list += $_ }
    $($num-1)..0 | foreach { $list += $_ }
    $numwrap = $list.count
   
 }
 
 $data = Get-Content $file 
 for($i=0; $i -le $data.count; $i++){
   if ($wrap) {
     $fnum = $list[$($i % $numwrap)]     
   }
   else { $fnum = $i % $num }

   $data[$i] | Out-File -FilePath $($outfiles[$fnum]) -Append
 }
}

All I did was add an array $list. If the –wrap switch is used this is populated by taking the values from the range of the number of files in a forward and reverse direction.

we then work out which file to use by doing the modulo arithmetic on the number of entries in list rather than in the outfile set.

other more sophisticated patterns could be devised if required.

Enjoy

Leave a Reply