Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I rename files in Powershell with regex?

I have some files with word characters and numbers at the end of filename. For some reason my regex is not working. Here are examples of my filenames:

test abc12345.zip
abcd def98765.zip
test xyz23456.zip

Here is my regex:

dir | rename-item -NewName {$_.name -replace "(\w\w\w\d\d\d\d\d.zip)","[$1].zip"}

When I run the selection snippet it removes:

abc12345
def98765
xyz23456

from the files names and just inserts the brackets:

test [].zip
abcd [].zip
test [].zip

How do I keep the contents within the brackets? Not sure why my code is removing everything in between the []

test [abc12345].zip
abcd [def98765].zip
test [xyz23456].zip
like image 985
user3683976 Avatar asked Oct 21 '25 05:10

user3683976


1 Answers

Replace the double quotes to single quotes. Powershell parses the content of double quotes and replaces your $1 with the content of the (non existent/empty) variable $1


Also, your regex can be made simpler to by using quantifiers for your word and digit characters so this

 (\w\w\w\d\d\d\d\d.zip)

can be changed to this shorter version

(\w{3}\d{5}.zip)

Looking at your expected output, there's another problem with your current capturing group that is including the .zip extension. What you actually want instead of capturing everything including the extension

(\w{3}\d{5}.zip)

is to capture only the word/digit part

(\w{3}\d{5}).zip

Now you can use the capturing group to put brackets around them. Your final regex and replacement might then look like this

dir | rename-item -NewName {$_.name -replace '(\w{3}\d{5}).zip','[$1].zip'}
like image 180
Lieven Keersmaekers Avatar answered Oct 23 '25 18:10

Lieven Keersmaekers