我有一个app.config,看起来像这样:
<!-- Device Configuration goes here -->
<DinoConfig Alpha="aaa" Beta="bbb" Gamma="ccc" Theta="">
<Dino Zeta="ooo" Delta="hhh" Tau="rrr" Rho="ddd" />
</DinoConfig>
现在我想将Beta更改为&#34; yyy&#34;和Gamma到&#34; zzz&#34;在DinoConfig父节点中使用批处理文件。此外,我想更改子节点(Dino)中的键值对。
我目前使用批处理脚本的方式:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "string=^<DinoConfig Alpha="nnn" Beta="mmm" Gamma="iii" Theta=""^>"
set "dir=%temp%" & set "file=Dino.config" & pushd "!dir!"
for /f "tokens=*" %%G in (%file%) do (set cstring=%%G
if "!cstring:~6,8!"=="Beta" set "cstring=%%G"
echo "!cstring!" | findstr /r /b /c:".*jjj.*" >nul 2>&1 && echo %string% || if defined cstring echo !cstring!
) >> %file:.config=_mod.config%
del %file% & ren %file:.config=_mod.config% %file% & popd
exit /b
使用这个我改变Beta =&#34; bbb&#34;在下一次迭代中我改变了=&#34; vvv&#34; (如果我可以同时更改两者,那将是很方便的。)
答案 0 :(得分:1)
下面的脚本对我很有用。将 dir 和文件值替换为您自己的目标文件保存在 dir 中,批处理文件可以从不同的文件夹:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "string= ^<Dino DinoName="mmm" Key1="nnn" Key2="pqr" Key3="stu" /^>"
set "dir=%temp%" & set "file=app.txt" & pushd "!dir!"
for /f "tokens=*" %%G in (%file%) do (set cstring=%%G
if "!cstring:~6,8!"=="DinoName" set "cstring= %%G"
echo "!cstring!" | findstr /r /b /c:".*jkl.*" >nul 2>&1 && echo %string% || if defined cstring echo !cstring!
) >> %file:.txt=_mod.txt%
del %file% & ren %file:.txt=_mod.txt% %file% & popd
exit /b
输出到文件:
<DinoConfig Key1="abc" Key2="def" Key3="ghi" >
<Dino DinoName="mmm" Key1="nnn" Key2="pqr" Key3="stu" />
<Dino DinoName="vww" Key1="xyz" Key2="aaa" Key3="bbb" />
</DinoConfig>
或者,您可以修改并尝试在问题中发布的脚本片段:
setlocal enabledelayedexpansion
for /f "tokens=*" %%i in ('findstr...
答案 1 :(得分:0)
对我有用的代码:
@echo off &setlocal
set "search=jkl"
set "replace=mmm"
(for /f "delims=" %%i in ('findstr "^" "%""C:\App.config""%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%""C:\NewApp.Config""%"
del c:\App.config & ren c:\NewApp.config App.config
set "search=mno"
set "replace=nnn"
(for /f "delims=" %%i in ('findstr "^" "%""C:\App.Config""%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%""C:\NewApp.Config""%"
del c:\App.config & ren c:\NewApp.config App.config