You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写batch脚本从txt提取配对标签内容输出指定格式

批处理提取标签内容配对输出解决方案

现有问题

你编写的代码会先提取所有game标签内容输出、再提取所有manufacturer标签内容输出,自然会出现所有同类型条目堆在一起的问题,需要改为逐行读取文件、配对相邻的game和manufacturer内容再输出。

你的原始需求

现有test.txt内容如下:

<game>16t (Japan)</game>
<manufacturer>Sega</manufacturer>
<game>3 Ninjas Kick Back</game>
<manufacturer>Malibu</manufacturer>

需要输出到output.txt的格式:

game: 16t (Japan)
developer: Sega

game: 3 Ninjas Kick Back
developer: Malibu

调整后的批处理代码

@echo off
setlocal enabledelayedexpansion
:: 清空旧输出文件
type nul > "%~dp0output.txt"
:: 暂存game内容的变量
set "game_content="
:: 逐行读取test.txt,以<>为分隔符拆分内容
for /f "tokens=1,* delims=<>" %%i in (test.txt) do (
    :: 匹配到game标签就暂存内容,剔除尾部的结束标签
    if "%%i"=="game" (
        set "temp=%%j"
        set "game_content=!temp:</game=!"
    )
    :: 匹配到manufacturer标签就和暂存的game内容配对输出
    if "%%i"=="manufacturer" (
        set "temp=%%j"
        set "dev_content=!temp:</manufacturer=!"
        echo game: !game_content! >> "%~dp0output.txt"
        echo developer: !dev_content! >> "%~dp0output.txt"
        :: 输出组间空行
        echo. >> "%~dp0output.txt"
    )
)
endlocal

内容的提问来源于stack exchange,提问作者zerohour27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:24:03