Indrasil
Indrasil

Reputation: 73

PowerShell - Remove certain string from multiple filenames

I have multiple .mp3 files in the catalogue and want to remove artist's name from their filenames. All the files' names contain string

"Adhesive Wombat - "

followed by the song's title. I want to remove (not replace) every occurence of that specific string in every filename in current folder.

Not to mention, I've searched for answer on this site and failed to find an elegant and satisfying solution.

This is my first encounter with PowerShell.

Upvotes: 7

Views: 22374

Answers (2)

budist
budist

Reputation: 81

From the above answers, the quick working example for simply copy&paste, that worked on win 10 Powershell:

  1. change directory to your target directory
  2. define files with e.g. *.txt or set all files with *.*
  3. insert your Strings for replacement
cd C:\.... 
Get-ChildItem *.* | Rename-Item -NewName {$_.Name -replace "StringtoReplace", "newString"}

Upvotes: 5

Matt
Matt

Reputation: 46710

As you know what you have is really close.

Dir | ren -NewName { $_.Name -replace "Adhesive Wombat - ", "" }

You added a stipulation that "Adhesive Wombat" may or may not contain a space. -replace uses regular expressions so lets harness that and make that space optional using a ?. I am also going to show you the full cmdlet name as supposed to aliases so you are aware of what is happening behind the scenes. It's hard to see but I tried to highlight the ? in bold for it to "pop".

Get-ChildItem | Rename-Item -NewName {$_.Name -replace "Adhesive ?Wombat - ", "" }

So that will match both

"other text Adhesive Wombat - other text "
"other text AdhesiveWombat - other text "

Also, depending on how much white space there is you could use \s+ where you have space which will match all consecutive white space.

Upvotes: 20

Related Questions