用于搜索字符串然后编辑它的批处理文件

时间:2013-11-18 21:51:54

标签: batch-file batch-updates

示例输入:

<document> 
 <filename>Admin Training Manual.pdf</filename>
 <type>0</type>
</document>
<document>
 <filename>Document Manual.pdf</filename>
 <type>0</type>
</document>

条件: 如果文件名为= Admin Training Manual,请将类型更改为1.

输出:

<document> 
 <filename>Admin Training Manual.pdf</filename>
 <type>1</type>
</document>
<document>
 <filename>Document Manual.pdf</filename>
 <type>0</type>
</document>

我已经尝试了一切,但无法找到答案。

我还没有尝试,但概念就在那里:

if header = <document> (
  loop to count line inside <document>
    if line is equal to 1 
    then check the string
      if match
      then replace line 2 with 1.     
)

2 个答案:

答案 0 :(得分:1)

@ECHO OFF &SETLOCAL
set "src=<filename>Admin Training Manual.pdf</filename>"
(for /f "delims=" %%a in (file.xml) do (
    set "line=%%a"
    SETLOCAL ENABLEDELAYEDEXPANSION
    if "!line!"=="!src!" set "flag=true"
    if not "!line:<type>=!"=="!line!" if defined flag (
        set "flag="
        set "line=<type>1</type>"
    )
    echo(!line!
    for /f %%b in ('set "flag" 2^>nul') do (if "!"=="" endlocal)&set "%%b"
))>out.xml

答案 1 :(得分:1)

@echo off
setlocal EnableDelayedExpansion

for /F "delims=:" %%a in ('findstr /N /C:"<filename>Admin Training Manual.pdf</filename>" input.txt') do set /A num=%%a+1

(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" input.txt') do (
   set "line=%%b"
   if %%a equ %num% set "line=!line:0=1!"
   echo !line!
)) > output.txt