首页 > 解决方案 > 从 txt 文件中提取特定字符串并将提取的字符串复制到批处理文件中的 json 文件中

问题描述

我有文本文件 abc.txt,其内容为:

abc.txt:

{"nature":"calm","trees":"uprooted from the main area","name":"usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj","enrolled":"not yet"}

我需要从 abc.txt 中提取与名称关联的字符串“usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj”。与 name 关联的字符串会有所不同,并且不是静态的。因此,无论字符串与 name 相关联,都必须在 sample.json 文件中提取和更新。

示例.json:

 {
   "requisite":{
            "name": "usdbuebcowecy821nkwh29y2bnso3ns389ye3wnsiwsn9usj"
               },
             "land": {
                    "key": "890"
                   }
}

Sample.json 文件名键应使用从 abc.txt 名称字段中提取的适当名称进行更新。

我尝试下面的代码片段来提取名称字段 abc.txt 文件:

For /f "tokens=1 delims=:" %%j in ('dir /b /s "C:\abc.txt" ^|findstr /I ""name":"') do echo "%%j" 
echo name is: %%j

但是循环不搜索名称字符串,我坚持继续进行。我是批处理脚本的新手。谁能帮我吗?

标签: jsonwindowsbatch-filecmd

解决方案


@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q64985945.txt"
:: Read sourcefile to LINE
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO SET "line=%%a"
:: Change each { } and : to comma
SET "line=%line:{=,%"
SET "line=%line:}=,%"
SET "line=%line::=,%"
:: ensure NAME is not defined
SET "name="
:: process LINE
:: set NAME when the string `name` is detected, use that flag to set NAME to the value following.
:: Note that LINE will not contain {:}, so any of these values can be used as a flag to detect
:: `name` as the last value.
FOR %%a IN (%line%) DO IF DEFINED name (SET "name=%%~a"&GOTO done ) ELSE IF /i "%%~a"=="name" SET "name=:"
:noname
ECHO No name value found
GOTO :eof
:done
SET name

GOTO :EOF

您需要更改设置sourcedir以适应您的情况。该清单使用适合我的系统的设置。

我使用了一个名为q64985945.txt包含您的数据的文件进行测试。

usebackq仅需要该选项,因为我选择在源文件名周围添加引号。

不幸的是,您仍然使 JSON 文本更加神秘。您发布的示例并没有告诉我们很多事情 - 是否第一次出现name是您需要的,或者是否有其他条件决定name要选择哪个特定值。例如,您的原始样本不包括嵌套的大括号对。在设计解决方案方面都非常重要......


推荐阅读