【问题标题】:Command Prompt Replace a String in the Middle of Filenames命令提示符替换文件名中间的字符串
【发布时间】:2021-06-19 15:23:33
【问题描述】:

我有一个包含数百个文件的文件夹,格式如下:

20210322 - Filename description.txt
20210321 - Filename description.txt
20210320 - Filename description.txt
20210319 - Filename description.txt
20210318 - Filename description.txt
...

使用 Windows 命令提示符,我如何将它们重命名为这种格式:

20210322 Filename description.txt
20210321 Filename description.txt
20210320 Filename description.txt
20210319 Filename description.txt
20210318 Filename description.txt
...

换句话说,替换,将“-”替换为“”。

以前用过

rename "IMG_*.jpg" "////*.jpg"

从文件名的开头删除“IMG_”。我尝试做类似的事情,但没有奏效:

rename "* - *.txt" "*/ /.txt"

【问题讨论】:

  • /-quirk 仅在您以 / 开头时才有效。使用for /F 循环:for /F "tokens=1* delims=- " %I in ('dir /B /A:-D-H-S "* - *.txt"') do ren "I% - %J" "%I %J"

标签: windows cmd rename


【解决方案1】:

我找到了更适合我的解决方案。一行,不需要批处理文件。使用 Windows Power Shell,输入:

Get-ChildItem -Recurse | ` Where-Object { $_.Name -match " - " } | ` Rename-Item -NewName { $_.Name -replace " - ", " " }

上述命令将替换所有文件名中的给定文本,包括子文件夹和子文件(递归)。

我希望它能够帮助某人。

【讨论】:

    【解决方案2】:

    使用已在受支持的 Windows 系统上的语言很容易做到这一点。 -replace 将删除 ' - '。如果您对正确重命名文件感到满意,请从 Rename-Item 命令中删除 -WhatIf

    powershell.exe -NoLogo -NoProfile -Command ^
        "Get-ChildItem -Path '.' -Filter '*.txt' |" ^
            "ForEach-Object {" ^
                "Rename-Item -Path $_.FullName -NewName $($_.Name -replace ' - ',' ') -WhatIf" ^
            "}"
    

    从 PowerShell 控制台或作为 .ps1 脚本运行时会更容易。

    Get-ChildItem -Path '.' -Filter '*.txt' |
        ForEach-Object {
            Rename-Item -Path $_.FullName -NewName $($_.Name -replace ' - ',' ') -WhatIf
        }
    

    要获得“单线”,请将上面的第一个代码示例放入一个文件中,例如 Do-Rename.bat 保存在 PATH 变量中提到的目录中。然后使用如下命令:

    Do-Rename
    

    【讨论】:

    • 是否有一个不错的单行代码可以使用“rename”或“ren”命令来做到这一点?
    猜你喜欢
    • 2015-08-07
    • 2017-03-06
    • 2013-12-27
    • 2017-04-01
    • 2010-11-17
    • 2023-04-11
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多