批处理文件替换文件名和扩展名中的字符串

批处理文件替换文件名和扩展名中的字符串

我正在尝试编写一个简单、小型且灵活的批处理文件,该文件易于针对不同的制造商进行修改,它将运行在 Proteus 中制作的 gerber 文件列表并对其进行适当的重命名。

此套适用于 Seeed Studio。

我遇到的问题是只有扩展被纠正,我需要替换整个字符串。

例如,“Circuit - CADCAM Bottom Copper.TXT”变为“Circuit.GBL”等等。

目前“电路 - CADCAM 底部铜.TXT”变为“电路 - CADCAM 底部铜.GBL”

谢谢您的帮助,

海丹

@echo off
Setlocal enabledelayedexpansion

REM Check all files are present and rename

set MISSING=0
call :CheckFile " - CADCAM Bottom Copper.TXT", ".GBL"
call :CheckFile " - CADCAM Bottom Copper", "-"
call :CheckFile " - CADCAM Bottom Silk Screen.TXT", ".GBO"
call :CheckFile " - CADCAM Bottom Solder Resist.TXT", ".GBS"
call :CheckFile " - CADCAM Drill.TXT", ".TXT"
call :CheckFile " - CADCAM Mechanical 1.TXT", ".GKO"
call :CheckFile " - CADCAM Top Copper.TXT", ".GTL"
call :CheckFile " - CADCAM Top Silk Screen.TXT", ".GTO"
call :CheckFile " - CADCAM Top Solder Resist.TXT", ".GTS"
REM if exist "Internal Plane 1.ger" call :CheckFile "Internal Plane 2.ger", ""

if %MISSING% EQU 0 (
    echo Success - all files found!
    pause
    goto :eof
) else (
    echo %MISSING% file^(s^) missing.
    pause
    goto :eof
)
REM Rename as found or flag erro

:CheckFile
if not exist *%1 (
    echo ERROR: Missing %1!
    set /a MISSING=%MISSING% + 1
) else (
    echo %1
    echo %2
    ren *%1 *%2
)

答案1

下一步:CheckFile程序应该可以完成这项工作:

:CheckFile
set "_string=%~1"
if not exist *%1 (
    echo ERROR: Missing %1!
    set /a MISSING+=1
) else (
    for /F "delims=" %%G in ('dir /B "*%~1"') do (
        set "_fileA=%%~G"
        set "_fileB=!_fileA:%_string%=!"
        rem next `rename` command is merely ECHOed for debugging purposes
        ECHO ren "%%~G" "!_fileB!%~2"
    )
)
goto :eof

笔记rename在上面的代码片段中,命令仅仅为了调试目的而被 ECHO;调试后立即删除前导ECHO(使用)!ren "%%~G" "!_fileB!%~2"

输出

==> D:\bat\SU\1119379.bat
ren "Circ #2 - CADCAM Bottom Copper.TXT" "Circ #2.GBL"
ren "Circuit - CADCAM Bottom Copper.TXT" "Circuit.GBL"
ren "Circuit - CADCAM Bottom Copper" "Circuit-"
ERROR: Missing " - CADCAM Bottom Silk Screen.TXT"
ERROR: Missing " - CADCAM Bottom Solder Resist.TXT"
ERROR: Missing " - CADCAM Drill.TXT"
ERROR: Missing " - CADCAM Mechanical 1.TXT"
ERROR: Missing " - CADCAM Top Copper.TXT"
ERROR: Missing " - CADCAM Top Silk Screen.TXT"
ERROR: Missing " - CADCAM Top Solder Resist.TXT"
7 file(s) missing.
Press any key to continue . . .

资源(必读,未完成):

相关内容