使用powershell减少文件名末尾的数字
我有一堆png文件,其中大多数都有以数字区分的共享文件名。例如,我可能有一些文件:使用powershell减少文件名末尾的数字,powershell,Powershell,我有一堆png文件,其中大多数都有以数字区分的共享文件名。例如,我可能有一些文件: 文件_A_01.png 文件_A_02.png 文件_B_1.png 文件_B_2.png 文件_C.png 不幸的是,这些都提供了从1开始的编号系统,我需要它从0开始。因此,我需要将我的文件重命名为: 文件_A_00.png 文件_A_01.png 文件_B_0.png 文件_B_1.png 文件_C.png (请注意,最终文件名中前导零的数量并不重要,但输入文件名中可能有混合。) 我已经找到了许多po
- 文件_A_01.png
- 文件_A_02.png
- 文件_B_1.png
- 文件_B_2.png
- 文件_C.png
- 文件_A_00.png
- 文件_A_01.png
- 文件_B_0.png
- 文件_B_1.png
- 文件_C.png
Get-ChildItem *.png |Rename-Item -NewName {$_.name -replace "([0-9]+).png",'$1.png'}
这当然没有任何作用——它只是匹配数字,然后用相同的数字替换它。我希望在结尾有类似于'$1'-1
的内容,但当然$1
是一个字符串。我不确定是否必须将其转换为整数,执行该操作,然后转换回字符串并替换它,如果是这样,我不知道如何执行该操作。(我对完全重写感到满意。)
由于我是powershell的完全初学者,我更喜欢清晰而不是直接,当然,对解决方案中步骤的任何解释都将不胜感激。尝试以下方法:
$Names = "file_A_01.png","file_A_02.png","file_B_1.png","file_B_2.png","file_C.png"
foreach($Name in $Names){
$Number = [Double]$([Regex]::Matches($Name, "\d+")).Value
if($Number -ne 0){
$Number = $Number - 1
$Name = $Name -replace $([Regex]::Matches($Name, "\d+")).Value , $Number
}
$Name
}
如果要保留前导零(将
A:\
更改为路径):
样本输出:
PS A:\> .\SO_44717299.ps1
What if: Performing the operation "Rename File" on target "Item: A:\file_A_01.png Destination: A:\file_A_00.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_A_02.png Destination: A:\file_A_01.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_B_1.png Destination: A:\file_B_0.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_B_2.png Destination: A:\file_B_1.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_C_001.png Destination: A:\file_C_000.png"
如果输出看起来正常,请删除重命名项后面的
-WhatIf
完美地回答了我的问题(而且非常清楚),尽管我如何更改它以处理包含其他数字的文件名?例如,如果我有一个文件“file_A1_01.png”,并希望它类似于“file_A1_0.png”。我会像这样拆分它$Number=($Name.split(“”)[2])。替换(“.png”,”),在$Number-1之后,我会将它放回原处
PS A:\> .\SO_44717299.ps1
What if: Performing the operation "Rename File" on target "Item: A:\file_A_01.png Destination: A:\file_A_00.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_A_02.png Destination: A:\file_A_01.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_B_1.png Destination: A:\file_B_0.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_B_2.png Destination: A:\file_B_1.png".
What if: Performing the operation "Rename File" on target "Item: A:\file_C_001.png Destination: A:\file_C_000.png"