I got files named like this:

cam1(word1 word2 wordN) (24-04-2012 00-11-13).mpg
cam2(word1 word2 wordN) (24-04-2012 00-11-13).mpg
cam3(word1 word2 wordN) (24-04-2012 00-11-13).mpg

Need to cut (word1 word2 word3) and replace spaces with _. Renamed files expected:

cam1_(24-04-2012_00-11-13).mpg
cam2_(24-04-2012_00-11-13).mpg
cam3_(24-04-2012_00-11-13).mpg

In the first pair of brackets there could be different number of "word". Timestamp is always the same.


Solution 1:

PowerShell allows you to do regex matches so it's easy to do this with Rename-Item:

Get-ChildItem *.mpg | Rename-Item -WhatIf -NewName `
  { $_.Name -replace '(.+?)\(.+?\) \((.+) (.+)\)', '$1_($2_$3)' }

You can also shorten the command with aliases:

> ls *.mpg | ren -wi -Ne `
    { $_.Name -replace '(.+?)\(.+?\) \((.+) (.+)\)', '$1_($2_$3)' }
What if: Performing the operation "Rename File" on target "Item: C:\Users\cam1(word1 word2 wordN) (24-04-2012 00-11-13).mpg Destination: C:\Users\cam1_(24-04-2012_00-11-13).mpg".
What if: Performing the operation "Rename File" on target "Item: C:\Users\cam2(word1 word2 wordN) (24-04-2012 00-11-13).mpg Destination: C:\Users\cam2_(24-04-2012_00-11-13).mpg".
What if: Performing the operation "Rename File" on target "Item: C:\Users\cam3(word1 word2 wordN) (24-04-2012 00-11-13).mpg Destination: C:\Users\cam3_(24-04-2012_00-11-13).mpg".

(.+?)\(.+?\) \((.+) (.+)\) is a regex that captures the first word and the two date time strings then we'll combine the matched strings together to get the expected output

-WhatIf or -wi is the option to do dry run. After checking that the new names are valid just remove them to do the real renaming