0

I'm trying to rename several files using a regex expression.

ck1823000-23.dat
ck1293834-67.dat
lo1230324-99.dat
pk1232131-34.dat
...

I want to remove -XX So the result would be like this:

ck1823000.dat
ck1293834.dat
lo1230324.dat
pk1232131.dat
...

I came up with this regex:

(?:.*?)([-\\s].*?).dat

But I get this error:

Rename-Item : The input to the script block for parameter 'NewName' failed. The regular expression pattern is not valid

When I run this command:

Get-ChildItem . -file -Filter "*.dat" | Rename-Item -newname { $_.name -replace "\(?:.*?)([-\\s].*?).dat\", ""}
0

2 Answers 2

1

Use the below regex and then replace the matched characters with an empty string.

-[^.-]*(?=\\.dat)

DEMO

Get-ChildItem . -file -Filter "*.dat" | Rename-Item -newname { $_.name -replace "-[^.-]*(?=\\.dat)", ""}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Works great. So I guess I can't use groups to match
I think you can. REgex : ^(.*?)([-\\s].*?)(\\.dat)$ replacemet string: $1$3 DEmo regex101.com/r/qM2pT8/2
1

Another option you can use basename instead of name property

Get-ChildItem . -file -Filter "*.dat" | 
   Rename-Item -newname { $_.basename -replace "-.*"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.