Windows批处理从文本文档重命名

时间:2016-11-09 00:49:09

标签: windows batch-file cmd

我制作了一个批处理脚本来重命名大量文件。它采用他们的名字并在文本文档中搜索它,复制该行并从中获取我需要的数据,然后重命名该文件。

它似乎在大多数情况下工作正常,但我无法检查它是如何做的,因为它在控制台中不断产生错误/警告。

@echo off
set ogg=.ogg
Setlocal EnableDelayedExpansion
for %%a in (*.ogg) do (
    set fileNameFull=%%a
    set fileName=!fileNameFull:~0,-4!
    for /F "delims=" %%a in ('findstr /I !fileName! strings.txt') do (
        endlocal
        set "stringLine=%%a%ogg%"
    )
    Setlocal EnableDelayedExpansion
    set fullString=!stringLine:~26!
    ren %%a "!fullString!"
)

pause

代码有效,我只想跟踪进度,因为一次重命名10,000个文件,而且我没有迹象表明这个过程有多远。

错误是:

"FINDSTR: Cannot open [...]"
"The syntax of the command is incorrect."

1 个答案:

答案 0 :(得分:0)

@echo off
Setlocal EnableDelayedExpansion
for %%a in (*.ogg) do (
    for /F "delims=" %%q in ('findstr /I /L /c:"%%~na" strings.txt') do (
     set "stringLine=%%q"
    )
    ECHO ren "%%a" "!stringLine:~26!.ogg"
)

pause

此代码应与您发布的代码等效,但已修复。

修正:

Removed the endlocal/setlocal complication - not required  
changed the inner `for` metavariable - must not be duplicate `%%a`  
Changed the `findstr` switches - add `/L` for literal and `/c:` to force single token in case of a separator-in-name; use `%%~na` to specify "the name part of `%%a`" to avoid the substringing gymnastics.
removed said gymnastics
Removed 2-stage string manipulation of destination filename
Removed superfluous setting of `ogg`

结果代码应该与原来的代码重复,除了它只是报告rename指令。您应该针对小型代表性样本进行测试以进行验证。

计算/进度:

set /a count=0
for %%a in (*.ogg) do (
    for /F "delims=" %%q in ('findstr /I /L /c:"%%~na" strings.txt') do (
     set "stringLine=%%q"
    )
    ECHO ren "%%a" "!stringLine:~26!.ogg"
    set /a count +=1
    set /a stringline= count %% 1000
    if %stringline% equ 0 echo !count! Processed
)

pause

应该显示每1000个进度。

您可以使用

    if %stringline% equ 0 echo !count! Processed&pause

在进行之前等待用户操作...

BTW-我假设新名称来自你文件中的第27列,因为你没有向我们展示样本。另外,你应该知道一个简单的findstr会找到将字符串作为文件中任意位置的子字符串 - 作为newname或oldname。如果您调用/B上的findstr开关,则字符串将仅在该行的最开头匹配。