Reputation: 29719
How can I rename each file in folder:
pattern is: (first part of file name).digit_(endoffilename)
for example
a.1_f
b.2_f
c.3_g
I would like to replace it with
a.01_f
b.02_f
c.03_ g
...
Thanks for help
Upvotes: 2
Views: 2396
Reputation: 201592
Try this:
Get-ChildItem | Where {!$_.PSIsContainer} |
Rename-Item -NewName {$_ -replace '([^.]+)\.(\d)(\w)', '$1.0$2$3'} -wh
Or if you have more than nine files:
gci | ? {!$_.PSIsContainer -and $_.Name -match '([^.]+\.)(\d)(\w+)'} |
rni -NewName {$matches[1] + ("{0:00}" -f [int]$matches[2]) + $matches[3]} -wh
The second example uses aliases to shorten the command (easier for typing). gci
is the alias for Get-ChildItem
, ?
is the alias for Where-Object
and rni
is the alias for Rename-Item
. The -wh
invokes the WhatIf
functionality where PowerShell will show you what it would do so you can twiddle with the command until you're happy with what the results would be. Then remove the -wh
to actually execute it.
Upvotes: 5
Reputation: 19117
One way to do this is to break the file apart via regular expressions, then assemble the new file name from the parts, followed by a Rename-Item
\w+\.\d+_\w
Get-ChildItem
& Foreach-Object
, or as I like to write ls | % {}
Upvotes: 0