批处理脚本以读取键并更新值

时间:2019-05-23 09:01:31

标签: windows batch-file

{
    "productVersion": "1.7.0",
    "examplePath": "somepath",
    "exampleBootloaderScript": "addin.js",
    "cachePath": "%APPDATA%\\example\\example",
    "logPath": "%APPDATA%\\example\\example\\Product\\Logs",
    "logLevel": "Info",
    "tempExcelCachePath": "%LOCALAPPDATA%\\example\\example5\\Cache",
    "exampleArgs": [
        "--devmenu",
        "--allow-insecure-localhost"
    ]
}

我想读取以上文件,并将键examplePath的值更新为此:

{
    "productVersion": "1.7.0",
    "examplePath": "D:\workspace\e5\sample\src\products\sample",
    "exampleBootloaderScript": "addin.js",
    "cachePath": "%APPDATA%\\example\\example",
    "logPath": "%APPDATA%\\example\\example\\Product\\Logs",
    "logLevel": "Info",
    "tempExcelCachePath": "%LOCALAPPDATA%\\example\\example5\\Cache",
    "exampleArgs": [
        "--devmenu",
        "--allow-insecure-localhost"
    ]
}

如何使用bat文件执行此操作?

1 个答案:

答案 0 :(得分:1)

如果somepath始终是静态的:

@echo off
set "_infile=YOURFILENAME HERE"
set "_strfind=somepath"
set "_strinsert=D:\workspace\e5\sample\src\products\sample"
for /f "tokens=2 delims=]" %%a in ('type "%_infile%" ^| find /v /n "" ^& break ^> "%_infile%"') do (
        set "str=%%a"
        call set "str=%%str:%_strfind%=%_strinsert%%%"
        setlocal enabledelayedexpansion
        echo(!str! >>%_infile%
        endlocal
)
type %_infile%

如果somepath可以是任何东西,我们需要更加具体并且专注于密钥,因此,只有文件的格式与您发布的格式相同时,这才起作用!当我们按字符串中的位置取键时。

因此,在继续之前,请对文件进行备份,因为如果格式不是您发布的格式,则会破坏该文件。

@echo off
set "_infile=YOURFILENAME HERE"
set "_strfind=examplePath"
set "_strinsert=    "examplePath": "D:\workspace\e5\sample\src\products\sample!","
for /f "tokens=2 delims=]" %%a in ('type "%_infile%" ^| find /v /n "" ^& break ^> "%_infile%"') do (
        set "str=%%a"
        setlocal enabledelayedexpansion
        if "!str:~5,11!"=="%_strfind%" (
            setlocal disabledelayedexpansion
            set "str=%_strinsert%"
        )
        setlocal enabledelayedexpansion
        echo(!str! >>%_infile%
        endlocal
)
type %_infile%

最后,我在某些部分使用delayedexpansion的原因纯粹是为了迎合包含!的行。