3

I have a series of files that I want to rename. I want to rename the files with padded zeroes after the first occurrence of the "-" delimiter like the example below:

Old Name: 101-1_File1_Project1-000-END.txt
Desired New Name: 101-001_File1_Project1-000-END.txt

I have PowerShell code that almost works, except it applies the padding to all the "-" instances and not just the first one. I've tried a million things and nothing worked. Please help!

PowerShell below:

gci "C:\Path\Folder-with-Files" | ren -n {[regex]::replace($_.basename, '\-', {"$args".PadRight(3, '0')})+ $_.extension}
LBro
  • 113
  • 6

1 Answers1

3

You can use a lookbehind:

gci "C:\Path\Folder-with-Files" | ren -n {[regex]::replace($_.basename, '(?<=^[^-]*)-', {"$args".PadRight(3, '0')})+ $_.extension}

The (?<=^[^-]*)- regex will match a - that is immediately preceded with a start of string (^) and then zero or more chars other than a hyphen.

See the .NET regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks so much - I was fiddling with the look behind and couldn't get it right. – LBro Aug 27 '21 at 21:22
  • do you know why {"$args".PadRight(3, '0')}) in this instance doesn't work with file names starting with 101-11 which actually become 101-0011 instead of 101-011 like I would expect? – LBro Aug 27 '21 at 22:58
  • 1
    @LBro: Your true intent is not to apply _right_-zero-padding to the first `-` instance, but to apply _left_-zero-padding to _the number that follows the first `-`_ - see [this answer](https://stackoverflow.com/a/68960613/45375) to your follow-up question. – mklement0 Aug 28 '21 at 01:28