简体   繁体   English

批处理脚本可一次查找和替换2个不同的字符串

[英]Batch script to find and replace 2 different strings at once

I have a XML file like this sample: 我有一个类似此示例的XML文件:

  <fruit>
      <desc>xxx / yyy / zzz</desc>
  </fruit>
  <fruit>
      <desc></desc>
  </fruit>
  <fruit>
      <desc>abc / def / ghi</desc>
  </fruit>

I'm using a batch script to fix the node "desc". 我正在使用批处理脚本来修复节点“ desc”。 This is the result after fixing: 这是修复后的结果:

  <fruit>    
      <desc>xxx/yyy/zzz</desc>    
  </fruit>    
  <fruit>    
      <desc>N/A</desc>    
  </fruit>    
  <fruit>    
      <desc>abc/def/ghi</desc>    
  </fruit>    

How can I replace 2 different strings without scan all the file twice? 如何替换2个不同的字符串而不扫描所有文件两次? This is the script: 这是脚本:

@echo off
setlocal enabledelayedexpansion

set "input_xml=xmlfile.xml"

set "search=^<desc^>^</desc^>"
set "search2= / "
set "replace=^<desc^>N/A^</desc^>"
set "replace2=/"
for /f "delims=" %%i in ('type "!input_xml!" ^& break ^> "!input_xml!" ') do (
  set FixNullNode=%%i
  echo !FixNullNode:%search%=%replace%! >>"!input_xml!" 
)
for /f "delims=" %%v in ('type "!input_xml!" ^& break ^> "!input_xml!" ') do (
  set FixSpaceSlash=%%v
  echo !FixSpaceSlash:%search2%=%replace2%! >>"!input_xml!" 
)
pause

Thanks 谢谢

Just move the second replace into the first for command. 只需将第二个替换项移入第一个for命令中即可。

@echo off
setlocal enabledelayedexpansion

set "input_xml=xmlfile.xml"

set "search=^<desc^>^</desc^>"
set "search2= / "
set "replace=^<desc^>N/A^</desc^>"
set "replace2=/"
for /f "delims=" %%i in ('type "!input_xml!" ^& break ^> "!input_xml!" ') do (
  set "Fix=%%i"
  set "Fix=!Fix:%search%=%replace%!"
  echo !Fix:%search2%=%replace2%! >>"!input_xml!" 
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM