[英]How to batch rename files in PowerShell starting with padded first numbers
I'm a PowerShell
newbie so please be gentle, I'm looking to bulk rename a collection of files.我是PowerShell
新手所以请保持温柔,我想批量重命名一组文件。 then pad the first digits so that they play in order on my devices.然后填充第一个数字,以便它们在我的设备上按顺序播放。
For example, I have a folder full of mp3s ABCDEF_S3L1_010221_GHIJK.mp3
through ABCDEF_S3L49_210921_GHIJK.mp3
例如,我有一个充满 MP3 的文件夹ABCDEF_S3L1_010221_GHIJK.mp3
到ABCDEF_S3L49_210921_GHIJK.mp3
I'm trying to rename them as 01-lesson.mp3
through 49-lesson.mp3
where the digit after the L
is the prefix but I trip up with the padding for lessons 1-9
so they play out of order, ie 01
then 10
, 11
, 12
etc. I've tried using variations of .PadLeft
and {0:D2}
but keep getting errors such as:我试图将它们重命名为01-lesson.mp3
到49-lesson.mp3
,其中L
之后的数字是前缀,但我在第1-9
课的填充中出错,所以它们播放顺序不正确,即01
然后10
、 11
、 12
等。我尝试使用.PadLeft
和{0:D2}
的变体,但不断收到以下错误:
Rename-Item: The filename, directory name, or volume label syntax is incorrect.
My code works without the initial padding:我的代码在没有初始填充的情况下工作:
PS G:\Temp\MP3s> Get-ChildItem -Path *.mp3 | Rename-Item
-NewName {$_.Name -replace '(^ABCDEF_S3L)(\d{1,2})_(\d{6})_(GHIJK)', '$2-lesson'}`
You can use -match
and by doing so capture the number behind the L
in $matches[1]
, which can be formatted like you want:您可以使用-match
并通过这样做捕获$matches[1]
中L
后面的数字,它可以按照您想要的格式进行格式化:
Get-ChildItem -Path 'D:\Test' -Filter '*.mp3' -File |
# apply better filename filter and capture the number after the 'L' in $matches[1]
Where-Object { $_.BaseName -match '^\w+_S\dL(\d+)_\d+_\w+' } |
Rename-Item -NewName { ('{0:D2}-lesson{1}' -f [int]$matches[1], $_.Extension) }
Cheating and going to powershell 7 with the scriptblock replace.用脚本块替换作弊并转到 powershell 7。 You just have to workout where the 2nd group match is within the $_
match object, which turns out to be $_.groups[2].value
.你只需要在$_
匹配 object 中的第二个小组比赛中锻炼,结果是$_.groups[2].value
。 Then you can use .padleft(2,'0')
on it.然后你可以在上面使用.padleft(2,'0')
。
# echo hi | set-content ABCDEF_S3L1_010221_GHIJK.mp3,
# ABCDEF_S3L49_210921_GHIJK.mp3
Get-ChildItem -Path *.mp3 |
% { $_.Name -replace '(^ABCDEF_S3L)(\d{1,2})_(\d{6})_(GHIJK)',
{ $a = $_ } }
.mp3
.mp3
$a
Groups : {0, 1, 2, 3, 4}
Success : True
Name : 0
Captures : {0}
Index : 0
Length : 25
Value : ABCDEF_S3L49_210921_GHIJK
Get-ChildItem -Path *.mp3 |
rename-item -newname {
$_.Name -replace '(^ABCDEF_S3L)(\d{1,2})_(\d{6})_(GHIJK)',
{ $_.groups[2].value.padleft(2,'0') + '-lesson' } } -whatif
What if: Performing the operation "Rename File" on target
"Item: C:\Users\js\foo\ABCDEF_S3L1_010221_GHIJK.mp3
Destination: C:\Users\js\foo\01-lesson.mp3".
What if: Performing the operation "Rename File" on target
"Item: C:\Users\js\foo\ABCDEF_S3L49_210921_GHIJK.mp3
Destination: C:\Users\js\foo\49-lesson.mp3".
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.