Search code examples
powershellfile-rename

How to rename multiple files at once and replace specific characters without affecting other characters


I want to replace the first two numbers on these 98 files that looks like this

10 10HZ.mp3
11 11HZ.mp3
12 12HZ.mp3

with "Bass Mekanik - " and make it look like this

Bass Mekanik - 10HZ.mp3
Bass Mekanik - 11HZ.mp3
Bass Mekanik - 12HZ.mp3

I've tried a lot of different combinations on CMD like this

*rename "?? ????.mp3" "Bass Mekanik - ????.mp3"

But nothing works. I want to keep the last 4 characters on every file.

Also in the near future I will need to add "Bass Mekanik - " in front of every file (not on these files, other files that have a lot of other characters) without changing anything else. So far I learned how to remove the first 2 characters using

*rename "?? ????.mp3" "// ????.mp3"

Then I tried adding "Bass Mekanik" but it gives an error "A duplicate file name exists, or the file cannot be found." I hope this is possible ...


Solution

  • This should do what you need, remove the WhatIf's if you're happy with the results

    Keep last 4 (8 with ".mp3") characters of filename and prefix with "Bass Mekanik "

    Get-ChildItem | % { $_.FullName -match ".{8}(?<=\.mp3$)" | Out-Null ; Rename-Item -LiteralPath $_.FullName -NewName ( "Bass Mekanik " + $Matches.Values ) -WhatIf }
    

    Prefix current filename with "Bass Mekanik "

    Get-ChildItem | % { Rename-Item -LiteralPath $_.FullName -NewName ("Bass Mekanik" + $_.Name ) -WhatIf }