批处理脚本以替换多个文件中的特定字符串 [英] Batch script to replace specific string in multiple files
问题描述
我对批处理脚本没有太多的经验,我的老板要求我编写一个批处理脚本,可以运行该脚本来查找和替换目录中所有匹配文件中的一些文本.
I don't have much experience with batch scripts, and my employer has asked me write a batch script that can be run to find and replace some text inside all matching files in the directory.
我尝试搜索此资源,并且有大量资源,我经常将其带到这里:
I've tried searching this and there's a tonne of resource, which I've used to get me this far:
@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
)
这将查找所有出现的<employeeloginid>0
,并在设置文件中将其替换为<employeeloginid>
-在这种情况下为TimeTEQ20170103T085714L.XML
.
This will find all occurrences of <employeeloginid>0
and replace it with <employeeloginid>
inside a set file - in this case TimeTEQ20170103T085714L.XML
.
我现在需要对此进行调整,以使其在以开头 TimeTEQ
和 .xml
I now need to tweak this to run on all files that start with TimeTEQ
and end with .xml
我找到了此答案,其中显示了如何处理目录中的所有文件,但我不知道该怎么做会对其进行调整以满足我的需求.
I found this answer which shows how to do all files in a directory, but I don't know how I would tweak it to suit my needs here.
有人可以帮我吗?
推荐答案
只需环绕一个标准 for
循环,即可:
Simply wrap around a standard for
loop, like this:
@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
如果您还希望在子文件夹中处理匹配文件,请使用 for /R
循环:
If you want to process matching files also in the sub-folders, use a for /R
loop:
@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
这篇关于批处理脚本以替换多个文件中的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!