Search code examples
regexpowershellrenamefile-renamebatch-rename

Regular Expressions Aren't Working in Bulk File Renaming


I'm missing something with my use of regex, because my line works when I replace defined strings. I tried \d and [0-9]. What am I forgetting?

Original FOOBAR_12345678-0001.csv

Goal 12345678.csv

get-childitem *.csv | foreach { rename-item $_ $_.Name.Replace("FOOBAR_(\d{8})-\d{4}", "$1") }

Solution

  • The following works for me:

    get-childitem *.csv | foreach { rename-item $_ ( $_.Name -replace 'FOOBAR_(\d{8})-\d{4}', '$1') }
    

    Why:

    1. I suspect the .Replace() method you were using doesn't take regexes.
    2. I'm not 100% sure it's necessary but I've made the practice of using single quotes with powershell regexes in case there is any shell expansion shenanigans going on.