Search code examples
regexpowershellrenamebulk

PowerShell Regex Bulk Replace Filenames


I am trying to replace filenames in a given folder, but using regular expressions as a filter and in the new filenames, in PowerShell.

For example, a file name "CEX-13" should be renamed to "C-0013"; "CEX-14" should change to "C-0014", etc.

I have this, but I get an error that I cannot create a file that already exists.

My current code is:

foreach ($file in get-childitem | where-object {$_.name -match "^CEX-(\d\d)"})
{
    rename-item $file -newname ($file.name -replace "^CEX-(\d\d)", "C-00$1")
}

Any help will be greatly appreciated.


Solution

  • You need the dollar in the replacement to get past the PowerShell variable expansion in strings, and stay as a dollar sign as it gets to the regex engine.

    Currently "C-00$1" becomes "C-00" and all the files will get the same name.

    You need to escape it with a backtick

    "C-00`$1"
    

    or use single quotes 'C-00$1'