Skip to content

Instantly share code, notes, and snippets.

@ToshY
Last active June 26, 2019 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToshY/1f91cb00f1018130a9ef1aa0e442d8d9 to your computer and use it in GitHub Desktop.
Save ToshY/1f91cb00f1018130a9ef1aa0e442d8d9 to your computer and use it in GitHub Desktop.
Batch rename files with regex replace
<#
.SYNOPSIS
Batch rename files with regex replace
.DESCRIPTION
BATCHREGEX makes it easy to batch rename your files using regex. Supply the directory of the files you need to rename; supply the regex expression you want applyp;
supply the new file names (including capturing groups as `$1, `$2, etc.; please note the backtick). Some experience with regex would be nice before using this.
Please note that the default mode for $safe_mode = 1, which means that it will show what happens when you'd rename the files but it will NOT execute the command.
When setting $safe_mode = 0, your regex will be executed so there's no turning back...
.EXAMPLE
In the following examples, pretend we have the following files "MyAwesomeVideo - 01 (somerubbish).mp4",..., "MyAwesomeVideo - 50 (somerubbish).mp4"
and we want to change it to "[COOL] ToishY vids - 01.mp4"
>> ISE
.\renameFiles.ps1 -path "F:\HomeVideos\ToishY" -rgx ".*- ``(\d{1,2}).*" -aname "[COOL] ToishY vids - `$1.mp4"
>> Windows CMD
powershell -executionpolicy bypass -File .\audio2video.ps1 -path "F:\HomeVideos\ToishY" -rgx ".*- (\d{1,2}).*" -aname "[COOL] ToishY vids - `$1.mp4" -safe_mode 1
>> Linux Terminal
pwsh renameFiles.ps1 -path "F:\HomeVideos\ToishY" -rgx ".*- (\d{1,2}).*" -aname "[COOL] ToishY vids - `$1.mp4" -safe_mode 0
.NOTES
Made this because I got pain in my hand from doing ctrl+c / ctrl+v everytime
.CREDITS
Made by: ToishY
Github: https://github.com/ToishY/batchregex
Last modified: 26-6-2019 22:08
#>
#------------- ARGUMENTS START ------------- #
param (
[Parameter(Mandatory=$true)]
[string]$path, #input dir
[Parameter(Mandatory=$true)]
[string]$rgx, #regex
[Parameter(Mandatory=$true)]
[string]$aname, #new name
[Parameter(Mandatory=$false)]
[string]$safe_mode = 1
)
if($safe_mode -eq 1){
# Safe verbose mode
Get-ChildItem -Path $path -Filter "*$ext" –File | Rename-Item -NewName { $_.name -replace $rgx, $aname } -WhatIf
}elseif($safe_mode -eq 0){
# The actual one-liner
Get-ChildItem -Path $path -Filter "*$ext" –File | Rename-Item -NewName { $_.name -replace $rgx, $aname }
}else{
Write-Error "Invalid value for argument `$safe_mode: $safe_mode. Should be 1 for safe mode, 0 for no-regrets mode."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment