Batch rename files with regex

4k views Asked by At

I have a number of files with the following format:

name_name<number><number>[TIF<11 numbers>].jpg

e.g. john_sam01 [TIF 15355474840].jpg

And I would like to remove the [TIF 15355474840] from all of these files This includes a leading space before the '[TIF...' and a different combination of 11 numbers each time.

So the previous example would become: josh_sam01.jpg


In short, using powershell (or cmd.exe) with regex I would like to turn this filename:

josh_sam01 [TIF 15355474840].jpg

Into this:

josh_sam01.jpg

With variables being: 'john' 'sam' two numbers and the numbers after TIF.

1

There are 1 answers

7
Richard On

Something like, with added newlines for clarity:

dir ‹parameters to select the set of files› |
   % {
     $newName = $_.Name -replace '\s\[TIF \d+\]',''
     rename-item -newname $newName -literalPath $_.Fullname
   }

Almost certainly adding -whatif to the rename until I was sure I had the file selection and rename correct.