Skip to content

Instantly share code, notes, and snippets.

@AustinSpafford
Last active April 16, 2018 05:19
Show Gist options
  • Save AustinSpafford/c79394adae3f852381a53d32457d5afe to your computer and use it in GitHub Desktop.
Save AustinSpafford/c79394adae3f852381a53d32457d5afe to your computer and use it in GitHub Desktop.
Utility for converting files with indices in their names to be the quotient/remainder of a divisor. This is useful if there's a large number of files that actually represent groups of 3/4/5/etc, and it'd be less confusing for them to be indexed by what group they're in.
param
(
[int]$divisor = 3,
[int]$indexingOrigin = 1, # Set to "0" if you want zero-based indexing, and likewise to "1" for one-based.
[bool]$padNumbers = $true
)
[regex]$indexRegex = "\d+"
Get-ChildItem -File -Recurse | ForEach-Object `
{
$fileItem = $_
Write-Host -NoNewLine "$($fileItem.Name), "
$regexMatch = $indexRegex.Match($fileItem.BaseName)
if ($regexMatch.Success)
{
$oldIndex = $regexMatch.Value
$newMainIndex = [int]([Math]::Floor(($oldIndex - $indexingOrigin) / $divisor) + $indexingOrigin)
# If desired, pad the output to the same number of digits as the input.
if ($padNumbers)
{
$newMainIndex = ([string]$newMainIndex).PadLeft($oldIndex.Length, '0')
}
$directoryName = Split-Path -Path $fileItem.PSPath
# Generate a new filename with an additional sub-index that avoids collisions with any existing file.
$newFilename = ""
for ($newSubIndex = $indexingOrigin; <# internal break #>; $newSubIndex++)
{
# Replace the first instance of the old index.
$newFilename = $indexRegex.Replace($fileItem.Name, "$($newMainIndex)_$($newSubIndex)", 1)
if (-Not (Test-Path (Join-Path $directoryName $newFilename) -PathType Leaf))
{
# The filename does't collide, so we'll accept it.
break
}
}
Write-Host "[$($oldIndex)], `"$($fileItem.Name)`" -> `"$($newFilename)`""
Rename-Item -Path $_.PSPath -NewName $newFilename
}
else
{
Write-Host "ignored"
}
}
Write-Host -NoNewLine "Press any key to exit...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment