使用批处理后启动exe替换配置文件中的行

时间:2013-12-18 10:16:44

标签: batch-file

使用批处理文件,我想更改配置文件中的值:

"title.connectionString" : "ServerIP",

ServerIP是要更改的变量。因此批处理文件必须为使用它的人提供从4个前缀IP中进行选择的选项。在他们选择4个IP之一后,配置文件必须以新值保存,批处理文件应运行可执行文件。

有人知道如何使用批处理文件执行此操作吗?

2 个答案:

答案 0 :(得分:0)

很简单,试试这段代码:

@echo off
:start
Echo Select Ip:
Echo.
Echo     1. 10.0.0.0
Echo     2. 10.0.0.1
Echo     3. 10.0.0.2
Echo     4. 10.0.0.1
Echo.
Choice /c 1234 /m "Ip: " /n 
set choice=%errorlevel%
set ip=
if %choice%==1 set ip=10.0.0.0
if %choice%==2 set ip=10.0.0.1
if %choice%==3 set ip=10.0.0.2
if %choice%==4 set ip=10.0.0.3
if "%ip%"=="" (Echo Error, null variable & goto :start) 

ren config.txt config.tmp
setlocal Enabledelayedexpansion
for /f "tokens=*" %%a in (config.tmp) do (
set line=%%a
Echo !line:ServerIP=%ip%! >> config.txt
)
del config.tmp

这应该做你想要的。

莫纳

答案 1 :(得分:0)

@echo off

    setlocal enableextensions

    call :replaceKeyValue "file.config" "title.connectionString" "123456789"

    endlocal

exit /b

:replaceKeyValue file key value
    setlocal enableextensions disabledelayedexpansion
    ren "%~f1" "%~nx1.tmp" >nul && (
        (for /f tokens^=1^,*^ delims^=^:^ eol^= %%k in ('findstr /n "^" ^<"%~f1.tmp"') do (
            echo(%%l|findstr /c:"\"%~2\"" >nul && (
                for /f "tokens=1 delims=:" %%v in ("%%l") do echo(%%~v : "%~3",
            ) || (
                echo(%%l
            )
        )) > "%~f1" 
        del "%~f1.tmp" > nul
    )
    endlocal

这将处理文件中值的替换。 Monacraft答案显示了选择所需IP的完美方式。

这会将文件重命名为file.tmp,并且对于文件中的每一行(findstr / n用于避免丢失空行),将再次测试传递的密钥。找到所需的行时,使用冒号(保持缩进)拆分,并用提供的值替换值。所有不匹配的行都按原样回显。该进程的所有输出都将发送到原始文件,最后,.tmp文件将被删除。