Cut a part from a filename

6,314

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

Share:
6,314

Related videos on Youtube

Igor
Author by

Igor

Updated on September 18, 2022

Comments

  • Igor
    Igor almost 2 years

    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.

    • mihi
      mihi about 12 years
      is PowerShell ok? In PowerShell you can use regular expressions for renaming. It might be possible in pure batch with a few nested For /F loops, or lots of %FOO:search=replace% in case the number of possible different words is small, but it would be definitely more ugly :)
  • Igor
    Igor about 12 years
    I need it to run it automatically from scheduler,
  • ZEDA-NL
    ZEDA-NL about 12 years
    I didn't realize that the words were different all the time. I modified the script so it should work now.
  • JonathanDavidArndt
    JonathanDavidArndt over 6 years
    BRU has some very basic command line options, but is not well suited to being run from a scheduler.
  • Scott - Слава Україні
    Scott - Слава Україні over 5 years
    Can you give an example of how something like this could be done with AutoHotkey?  Please do not respond in comments; edit your answer to make it clearer and more complete.