config.txt文件内容
[Common]
ITEM1=ITEM1
ITEM2=ITEM2
ITEM3=ITEM3
bat文件内容
@echo off
CALL :readconfig ITEM1 ITEM1_VALUE
@ECHO %ITEM1_VALUE%
pause
:readconfig for /f "skip=1 tokens=1,2 delims==" %%a IN (config.txt) Do if %1==%%a set %2=%%b & @echo read config get %%a, value is %%b
goto :eof
//说明
for /f "skip=1 tokens=1,2 delims==" %%a IN (config.txt) Do
for..Do 循环 /f 读文件
(config.txt) 文件名,括号起来
skip=1 跳过第一行
delims== 取一行数据后用=号进行分割
tokens 分割以后取第1,2个数值 也可以2,3 或者2-10
if %1==%%a set %2=%%b & @echo read configget %%a, value is %%b
%1 传入的第一个参数
%%a 分割后的第一个值
set %2=%%b 将分割后的第二个值%%b赋给传入的第二个参数%2
自己做的一个测试,备份文件
copyBK.bat
@echo off Set configPath=D:\web\configBK.txt Set targetChar=/ Set replaceChar=\ Set TargetFolder=D:\web\bk Set SourceFolder=C:\test call replace.bat %configPath% %targetChar% %replaceChar% call :readconfig %configPath% %TargetFolder% %SourceFolder% pause&exit :readconfig Set i=0 for /f "tokens=1" %%a IN (%1) Do if exist %3\%%a ((xcopy %3\%%a %2\%%a /s /e /i /y) & Set /a i=i+1) @echo copied %i% files pause & exit
replace.bat
@echo off @echo start replace... setlocal enabledelayedexpansion set file=%1 set "file=%file:"=%" for %%i in ("%file%") do set file=%%~fi echo. set replaced=%2 echo. set all=%3 for /f "delims=" %%i in ('type "%file%"') do ( set str=%%i set "str=!str:%replaced%=%all%!" echo !str!>>"%file%"_tmp.txt ) copy "%file%" "%file%"_bak.txt >nul 2>nul move "%file%"_tmp.txt "%file%" @echo. @echo end replace @echo. @echo.
configBK.txt
job/job.cs job/job.aspx