【问题标题】:How to batch rename files to remove special characters with powershell如何使用powershell批量重命名文件以删除特殊字符
【发布时间】:2020-05-26 09:45:39
【问题描述】:

只是想更改一堆以

开头的文件
02. SongName.Mp3
02 - OtherName.Mp3
02 MoreNames.Mp3
03. Song.mp3
03 - Songs.mp3

SongName.Mp3
OtherName.Mp3
MoreNames.Mp3
Song.mp3
Songs.mp3

我知道这是一个非常简单的 [ren] 命令,但它在我的脑海中消失了。我在文件夹上使用 file>open>powershell,所以不需要使用 dir 或 cd 或任何东西。

【问题讨论】:

    标签: windows powershell rename


    【解决方案1】:
    Get-ChildItem *.mp3 | Rename-Item -NewName { $_.Name -replace '^[^\p{L}]+' } -WhatIf
    

    注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

    以上通过从文件名中删除第一个字母 (\p{L}) 之前 的任何字符来重命名*.mp3 文件;名称已经以字母开头的文件保持不变。

    使用的技术:

    【讨论】:

      【解决方案2】:

      我会努力解决的。假设所有文件都是 mp3,将数字、点、破折号和空格替换为空。 (或“复制项-目的地”)

      # test files
      # echo hi | set-content '02. SongName.Mp3','02 - OtherName.Mp3','02 MoreNames.Mp3','03. Song.mp3','03 - Songs.mp3'
      
      dir *.mp3 | rename-item -newname { ($_.basename -replace '[\d\.\- ]') + '.mp3' } -whatif
      
      What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/02 - OtherName.Mp3 Destination: /Users/js/foo/OtherName.mp3".
      What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/02 MoreNames.Mp3 Destination: /Users/js/foo/MoreNames.mp3".
      What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/02. SongName.Mp3 Destination: /Users/js/foo/SongName.mp3".
      What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/03 - Songs.mp3 Destination: /Users/js/foo/Songs.mp3".
      What if: Performing the operation "Rename File" on target "Item: /Users/js/foo/03. Song.mp3 Destination: /Users/js/foo/Song.mp3".
      
      

      【讨论】:

        【解决方案3】:
           Get-ChildItem *.mp3 |
             Where-Object Name -match '^.{4}(.+).\.(.+)$' | 
               Copy-Item -Destination { $Matches.1 + '.' + $Matches.2 }
        

        这适用于我想要做的事情。特别注意,它会复制文件,不会重命名现有文件。

        【讨论】:

        • 这不适用于'02 MoreNames.Mp3',例如;最好不要依赖固定的字符位置,而是按字符 type 进行匹配,如我的回答所示。
        • 不是我投了反对票,但出于上述原因,我确实认为您的解决方案不是最理想的(而且还可以通过使用带有 @987654325 的延迟绑定脚本块来提高效率@ 而不是 Where-Object 调用)。也就是说,即使在这种情况下我不推荐它,您仍然可以在发布 48 小时后接受您自己的答案。请允许我在下一条评论中给你标准的建议给新人。
        • 如果某个答案解决了您的问题,请accept it 点击旁边的大复选标记 (✓) 并可选择对其进行投票(投票至少需要 15 个声望点)。如果您发现其他答案有帮助,请给他们投票。接受(您将获得 2 个声望点)和投票可以帮助未来的读者。如果您的问题尚未得到完全解答,请提供反馈或self-answer
        猜你喜欢
        • 1970-01-01
        • 2017-02-21
        • 2016-10-18
        • 1970-01-01
        • 2010-11-19
        • 2015-09-24
        • 1970-01-01
        • 2013-12-09
        • 1970-01-01
        相关资源
        最近更新 更多