批处理脚本替换多个文件中的特定字符串

Jam*_*mes 5 windows cmd batch-file

我对批处理脚本没有太多经验,我的雇主要求我编写一个批处理脚本,可以运行该脚本来查找和替换目录中所有匹配文件中的某些文本。

我尝试搜索此内容,并且有大量资源,我用这些资源到目前为止:

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=<employeeloginid>0"
    set "replace=<employeeloginid>"

    set "textFile=TimeTEQ20170103T085714L.XML"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:%search%=%replace%!"
        >>"%textFile%" echo(!line!
        endlocal
    )
Run Code Online (Sandbox Code Playgroud)

这将找到所有出现的<employeeloginid>0并将其替换为集合文件<employeeloginid>中的内容- 在本例中。TimeTEQ20170103T085714L.XML

我现在需要调整它以在所有以以下开头 TimeTEQ结尾的文件上运行 .xml

我发现这个答案显示了如何处理目录中的所有文件,但我不知道如何调整它以满足我的需要。

有人可以帮我吗?

asc*_*pfl 6

只需环绕一个标准for循环,如下所示:

@echo off 
setlocal EnableExtensions DisableDelayedExpansion

set "search=<employeeloginid>0"
set "replace=<employeeloginid>"

set "textFile=TimeTEQ*.xml"
set "rootDir=."

for %%j in ("%rootDir%\%textFile%") do (
    for /f "delims=" %%i in ('type "%%~j" ^& break ^> "%%~j"') do (
        set "line=%%i"
        setlocal EnableDelayedExpansion
        set "line=!line:%search%=%replace%!"
        >>"%%~j" echo(!line!
        endlocal
    )
)

endlocal
Run Code Online (Sandbox Code Playgroud)

如果您还想处理子文件夹中的匹配文件,请使用for /R循环

@echo off 
setlocal EnableExtensions DisableDelayedExpansion

set "search=<employeeloginid>0"
set "replace=<employeeloginid>"

set "textFile=TimeTEQ*.xml"
set "rootDir=."

for /R "%rootDir%" %%j in ("%textFile%") do (
    for /f "delims=" %%i in ('type "%%~j" ^& break ^> "%%~j"') do (
        set "line=%%i"
        setlocal EnableDelayedExpansion
        set "line=!line:%search%=%replace%!"
        >>"%%~j" echo(!line!
        endlocal
    )
)

endlocal
Run Code Online (Sandbox Code Playgroud)