【问题标题】:How to batch rename files in PowerShell starting with padded first numbers如何在PowerShell中以填充的第一个数字开始批量重命名文件
【发布时间】:2021-11-18 20:09:36
【问题描述】:

我是PowerShell 新手所以请温柔一点!我希望批量重命名一组文件,然后填充第一个数字,以便它们在我的设备上按顺序播放。

例如,我有一个完整的 mp3 文件夹 ABCDEF_S3L1_010221_GHIJK.mp3 到 ABCDEF_S3L49_210921_GHIJK.mp3

我正在尝试将它们重命名为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.

我的代码在没有初始填充的情况下工作:

PS G:\Temp\MP3s> Get-ChildItem -Path *.mp3 | Rename-Item
-NewName {$_.Name -replace '(^ABCDEF_S3L)(\d{1,2})_(\d{6})_(GHIJK)', '$2-lesson'}`

【问题讨论】:

    标签: powershell rename-item-cmdlet


    【解决方案1】:

    您可以使用-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) }
    

    【讨论】:

      【解决方案2】:

      作弊并使用脚本块替换进入 powershell 7。您只需要在$_ 匹配对象内的第二组比赛中进行锻炼,结果是$_.groups[2].value。然后你可以在上面使用.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".
      

      【讨论】:

        猜你喜欢
        • 2014-07-01
        • 1970-01-01
        • 2015-04-14
        • 2021-10-27
        • 2010-11-19
        • 2020-12-26
        • 2020-04-06
        • 1970-01-01
        相关资源
        最近更新 更多