Regex to Exclude something and bulk rename files

Viewed 156

I'm trying to rename all files of a directory, remove parts of files names excluding some parts.

for example:

Before --> After 

file1: Something S01E01 Hello There Guys.srt --> S01E01.srt

file2: Something_else S03E22 Good.bye.srt --> S03E22.srt

etc.

I tried following code in powershell:

Get-ChildItem | rename-item -NewName {$_.name -replace "Something",""}
Get-ChildItem | rename-item -NewName {$_.name -replace "Good.bye",""}
Get-ChildItem | rename-item -NewName {$_.name -replace "Something_else",""}
Get-ChildItem | rename-item -NewName {$_.name -replace " Hello(.*?)\.srt",".srt"}
Get-ChildItem | rename-item -NewName {$_.name -replace " ",""}

Any idea about the right regex code instead of hardcoding to exclude "SxxExx.srt" Part of file name and remove the other parts of name?

2 Answers

Maybe,

\b[A-Z][0-9]+[A-Z][0-9]+\b\s*|\.srt

or,

\b[A-Z][0-9]+[A-Z][0-9]+\b\s*|\.srt[^\r\n]*

or some similar expression being replaced with an empty string might be somewhat close.

Demo 1

Demo 2

You'll want to use a pattern like this:

(S\d{2}E\d{2})

to match and capture the S01E01 part.

Get-ChildItem | Rename-Item -NewName {($_.BaseName -replace '^.*(S\d{2}E\d{2}).*$','$1') + $_.Extension}
Related