PowerShell File Rename with Padded Zeroes After First Delimeter

Viewed 76

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}
1 Answers

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.

Related