Search code examples
powershellfilefile-renameexact-match

Replace exact part of file name with Powershell


I tried the code found here without success.

What I need is to replace an exact text with another, but this code doesn't seem to deal with exact text.

This is the code I used, and what I need is, for example, for a file name that ends with ".L.wav" to be replaced with "_L.wav", but what happens is that powershell tries to rename even the file that ends with ".BL.wav" into "_L.wav".

Thank you.

ls *.* | Rename-Item -NewName {$_.name -replace ".L.wav","_L.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".LFE.wav","_LFE.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".R.wav","_R.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".BL.wav","_LSR.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".BR.wav","_RSR.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".SL.wav","_LSS.wav"}
ls *.* | Rename-Item -NewName {$_.name -replace ".SR.wav","_RSS.wav"}
Read-Host -Prompt "Press Enter to exit" ```

Solution

  • The dot in regex means Any Character. Without escaping that, things go wrong.

    Try

    Rename-Item -NewName {$_.Name -replace ('{0}$' -f [regex]::Escape('.L.wav')),'_L.wav'}
    

    or manually escape the regex metacharacters:

    Rename-Item -NewName {$_.Name -replace '\.L\.wav$','_L.wav'}
    

    The $ at the end anchors the text to match at the end on the string

    Also, instead of doing ls *.* | Rename-Item {...}, better use

    (Get-ChildItem -Filter '*.L.wav' -File) | Rename-Item {...}
    

    (ls is alias to Get-ChildItem )

    • Using the -Filter you can specify what files you're looking for.
    • Using the -File switch, you make sure you do not also try to rename folder objects.
    • By surrounding the Get-ChildItem part of the code in brackets, you make sure the gathering of the files is complete before you start renaming them. Otherwise, chances are the code will try and keep renaming files that are already processed.