需要使用Powershell向文件名中批量添加字符

问题描述 投票:0回答:2

我有一系列文件都以类似的方式命名:

PRT14_WD_14220000_1.jpg

我需要在最后一个下划线之后和数字之前添加两个零,因此看起来像PRT14_WD_14220000_001.jpg

我尝试过]

(dir) | rename-Item -new { $_.name -replace '*_*_*_','*_*_*_00' }

感谢任何帮助。

powershell filenames
2个回答
0
投票
与您尝试的最接近的事情就是这个。在正则表达式中,通配符为.*。括号进行分组,以便以后使用美元符号编号进行引用。

dir *.jpg | rename-Item -new { $_.name -replace '(.*)_(.*)_(.*)_','$1_$2_$3_00' } -whatif What if: Performing the operation "Rename File" on target "Item: C:\users\admin\foo\PRT14_WD_14220000_1.jpg Destination: C:\users\admin\foo\PRT14_WD_14220000_001.jpg".


0
投票
以下假定.BaseName的最后部分将始终需要添加两个零。它做什么...

    假冒获取从fileinfo获得的Get-Item/Get-ChildItem对象将其替换为适当的cmdlet。 [
  • 咧嘴]
  • 使用.BaseName作为分割目标,将_分割为多个部分
  • 将两个零添加到上述拆分的最后一个部分中
  • 将零件合并为$NewBaseName
  • 获取.FullName并将原始BaseName替换为$newBaseName
  • 显示该新文件名
  • 您仍然需要重新命名,但这很直接。 [

    咧嘴]

    这是代码...

    # fake getting a file info object # in real life, use Get-Item or Get-ChildItem $FileInfo = [System.IO.FileInfo]'PRT14_WD_14220000_1.jpg' $BNParts = $FileInfo.BaseName.Split('_') $BNParts[-1] = '00{0}' -f $BNParts[-1] $NewBasename = $BNParts -join '_' $NewFileName = $FileInfo.FullName.Replace($FileInfo.BaseName, $NewBaseName) $NewFileName

    输出= D:\Data\Scripts\PRT14_WD_14220000_001.jpg
  • © www.soinside.com 2019 - 2024. All rights reserved.