使用批处理文件替换 app.config 中的键值对

Replacing key-value pair in app.config using a batch file

我有一个 app.config 看起来像这样:

   <!-- Device Configuration goes here --> 
         <DinoConfig Alpha="aaa" Beta="bbb" Gamma="ccc" Theta="">
      <Dino Zeta="ooo" Delta="hhh" Tau="rrr" Rho="ddd" />
    </DinoConfig>

现在我想在 DinoConfig 父节点中使用批处理文件将 Beta 更改为 "yyy" 并将 Gamma 更改为 "zzz"。我也想更改子节点 (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="bbb" 并且在下一次迭代中我正在更改 ="vvv" (如果我可以同时更改两者会很方便)。

下面的脚本很适合我。将 dirfile 值替换为您自己的值,目标 file 保存在 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...

对我有用的代码:

@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