代码之家  ›  专栏  ›  技术社区  ›  Zachary

如果文件名缺少字符串,请使用批处理文件重命名文件

  •  1
  • Zachary  · 技术社区  · 12 年前

    我正在尝试编写一个批处理文件,如果文件名末尾不包含特定字符串,则该文件将重命名文件名。例如,我有一个文件夹,其中包含以下文件:

    测试文件1.csv
    测试文件2 Zac.csv

    对于每一个结尾(扩展名之前)不包含“Zac”(没有引号)的文件,我想在文件名中添加“Zac”。因此,结果将是:

    测试文件1 Zac.csv
    测试文件2 Zac.csv

    这是我当前拥有的批处理文件:

    for %%f in (*.csv) do (ren "%%f" ???????????????????????????????" Zac.csv"
    

    但这会将“Zac”添加到所有文件中,即使它们已经包含“Zac“。如何只更改那些末尾没有“Zac”的文件?

    非常感谢你!

    3 回复  |  直到 12 年前
        1
  •  3
  •   Endoro    12 年前
        for /f "delims=" %%a in ('dir /b /a-d *.csv ^|findstr /iv "zac"') do echo ren "%%~a" "%%~na Zac%%~xa"
    

    查看输出并移除 echo 如果它看起来不错。
    注意:如果文件已经存在 ren 失败,您会收到一条错误消息。

        2
  •  0
  •   Community CDub    8 年前

    这应该起作用:

    @echo off
    : create variable to track number of files renamed
    set filesRenamed=0
    : loop through csv files and call Rename routine
    for %%f in (*.csv) do call :Rename "%%f" filesRenamed
    : output results
    echo %filesRenamed% files renamed
    : clear variables
    set filesRenamed=
    set tmpVar=
    : Goto end of file so we don't call rename an extra time
    goto :eof
    
    :Rename
    : need a local environment variable with filename for manipulation
    set tmpVar=%1
    : remove the closing quotes
    set tmpVar=%tmpVar:~0,-1%
    : compare the last 8 characters and rename as necessary
    if /I NOT "%tmpVar:~-8%" EQU " Zac.csv" (
        : use original file name parameter which is already quoted
        ren %1 ???????????????????????????????" Zac.csv"
        : increment the renamed file count
        set /A %2=%2+1
    )
    

    看见 this other post 以便很好地描述批处理文件中的子字符串处理。

        3
  •  0
  •   Lloyd    12 年前

    使用 renamer ,这些输入文件:

    Test File1 Zac.csv
    Test File2.csv
    Test File3.csv
    Test File4.xls
    Test File5 Zac.csv
    

    使用此命令:

    $ renamer --regex --find '(Test File\d)(\.\w+)' --replace '$1 Zac$2'  *
    

    导致以下新文件名:

    Test File1 Zac.csv
    Test File2 Zac.csv
    Test File3 Zac.csv
    Test File4 Zac.xls
    Test File5 Zac.csv
    

    如果你还需要帮助,请告诉我。