Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

Remove parentheses in powershell regex?

I cant find a find an answer that is clear to me. I am changing a bunch of image file names in a directory, when I rename them they all get renamed to image (1).png image (2).png for as many images as I have then I run this in power shell.

Dir | Rename-Item –NewName { $_.name –replace " ","_" }

This finds the space and renames it to image_(1).png image_(2).png nice and easy, but It becomes a headache trying to replace the parentheses. I am trying to get rid of them to look like this image_1.png image_2.png but it's gotten really frustrating finding an answer lol.

I wish I could just write.

Dir | Rename-Item –NewName { $_.name –replace "\(*\)","*" } 

or

Dir | Rename-Item –NewName { $_.name –replace "\([1-10]\)","[1-10]" }

or

Dir | Rename-Item –NewName { $_.name –replace "\(\W\)","\W" }

I tried them all and you would think that syntax is valid, but nope :( So I am hoping for a little nudge in the right direction.

Upvotes: 3

Views: 15035

Answers (4)

PSNewb
PSNewb

Reputation: 45

Couldn't comment under the answer but this is a way to getting rid of the "()" and the text inside in one go.

Rename-Item –NewName { $_.name -replace "(\(\d+\))",""}

The \( and \) escapes the parentheses making them literal parentheses. The non-escaped parentheses group the captured pattern to be referenced later and may not be needed here for what you are doing.

Hope this helps someone.

Upvotes: 2

tiagorockman
tiagorockman

Reputation: 361

I did with two lines
Dir | Rename-Item –NewName { $.name –replace "(","" } Dir | Rename-Item –NewName { $.name –replace ")","" }

Upvotes: 0

mjolinor
mjolinor

Reputation: 68243

How about:

Dir | Rename-Item –NewName { $_.name.replace(' ','_') -replace '[()]','' }

The string .replace() method is much more efficient for single literal character replacement. Use the -replace operator for more complex operations where you need to specify multiple characters at once.

Upvotes: 5

Jon Upchurch
Jon Upchurch

Reputation: 450

I don't have enough SO Rep to comment on your question so I have to try for an answer. Do you need to escape your backslashes? ie. Replace

"\(*\)","" with "\\(*\\)",""

Is your issue with the command syntax or the Regex itself? The raw Regex would look something like this:

^(?\<Name>.*)\((?<Number>\d*?)\)\.(?<Extension>.*$)

and replace with: ${Name}_${Number}.${Extension}

Upvotes: 8

Related Questions