批量提取 XML 文件中特定字符串 - 批处理脚本教程

使用批处理中的字符串提取和替换命令可以轻松地从 .xml 文件中批量提取特定字符串。本文将以提取 <ProductKey>N4KHB-KFRGM-QRDGC-TRBRT-FVWGG</ProductKey> 中的 N4KHB-KFRGM-QRDGC-TRBRT-FVWGG 为例,介绍如何使用批处理脚本实现这一功能。

批处理脚本

@echo off
setlocal enabledelayedexpansion

set "searchString=N4KHB-KFRGM-QRDGC-TRBRT-FVWGG"
set "replaceString=NewString"

set "folderPath=C:\Path\to\Your\Folder"

for %%F in ("%folderPath%\*.xml") do (
    set "filePath=%%F"
    set "tempFile=%%~dpnF_temp.xml"
    
    REM 提取并替换内容
    findstr /C:"<ProductKey>%searchString%</ProductKey>" "!filePath!" > "!tempFile!"
    if exist "!tempFile!" (
        copy /Y "!tempFile!" "!filePath!" > nul
        del "!tempFile!"
        
        REM 输出替换结果
        echo Replaced in: "!filePath!"
    ) else (
        echo Not found in: "!filePath!"
    )
)

 echo Batch processing completed.
pause

脚本说明

  • searchString:要提取和替换的字符串。
  • replaceString:要替换的新字符串。
  • folderPath:要批量处理的文件夹路径。

使用方法

  1. 将上述代码保存为 .bat 文件。
  2. 修改 searchString、replaceString 和 folderPath 变量的值。
  3. 双击运行 .bat 文件,即可批量处理 .xml 文件。

注意

  • 在运行批处理之前,请务必备份您的文件,以防意外情况发生。
  • 该脚本仅替换每个文件中的第一个匹配项。
  • 如果您需要进行其他操作,例如提取多个匹配项,请根据实际需求修改脚本代码。

原文地址: https://www.cveoy.top/t/topic/pleu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录