2017-04-04 44 views
2

我想創建一個批處理腳本,它將執行以下操作: 查找特定的xml行,並添加特定的多行標記。在特定行後批量添加xml行

例如:中準確找到這個套系:

<tree_node> 
    <rule_name>bla</rule_name> 
    <rule_argument>bla</rule_argument> 
    <acl_name>bla</acl_name> 
</tree_node> 

然後添加此套系算賬:

<tree_node> 
    <rule_name>TEST1</rule_name> 
    <rule_argument>TEST2</rule_argument> 
    <acl_name>TEST3</acl_name> 
</tree_node> 

另一種解決辦法是在一個特定的行號插入標籤。 任何人都可以提供解決方案嗎?我搜查了,但沒有發現任何關於我的問題。

感謝您的幫助!下面

+0

相關dbenham的回答是::[請注意

例如,如果在文件中只有一個<rule_name>bla</rule_name>段,在這段代碼,則相同的五線搜索字符串可與該短文本定義 - 使用批解析XML是一項有風險的業務](http://stackoverflow.com/a/26718487/3439404) – JosefZ

+0

爲什麼不使用可以正確讀寫XML文件的腳本語言? Vbscriipt,Jscript,Powershell。 – Squashman

+0

這將是可能的Powershell - 但我沒有任何知識如此做。任何例子都會受到歡迎。謝謝! – Nikec123

回答

0

批處理文件做正是你要求:

@echo off 
setlocal EnableDelayedExpansion 

rem Define CR variable containing a Carriage Return (0x0D) 
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a" 

rem Define LF variable containing a Line Feed (0x0A) 
set LF=^ 
%Do not remove% 
%these lines% 

rem Define the string to find 
set "find=<tree_node>!CR!!LF!" 
set "find=!find! <rule_name>bla</rule_name>!CR!!LF!" 
set "find=!find! <rule_argument>bla</rule_argument>!CR!!LF!" 
set "find=!find! <acl_name>bla</acl_name>!CR!!LF!" 
set "find=!find!</tree_node>" 

rem Get the number of lines to copy 
findstr /N /R /C:"!find!" input.txt > findstr.tmp 
for /F "delims=:" %%a in (findstr.tmp) do set /A lines=%%a+4 
del findstr.tmp 

rem Read from input file 
< input.txt (

    rem Copy the appropriate number of lines 
    for /L %%i in (1,1,%lines%) do (
     set /P "line=" 
     echo !line! 
    ) 

    rem Add the new lines 
    echo ^<tree_node^> 
    echo  ^<rule_name^>TEST1^</rule_name^> 
    echo  ^<rule_argument^>TEST2^</rule_argument^> 
    echo  ^<acl_name^>TEST3^</acl_name^> 
    echo ^</tree_node^> 

    rem Copy the rest of lines 
    findstr "^" 

rem Write to output file 
) > output.txt 

move /Y output.txt input.txt 

有關用來尋找多行字符串的方法進一步說明,請參見this answer

EDIT如何定義一個較大的搜索文本

findstr命令具有用於在文件中要搜索的文本的多行的字符串的長度的限制。但是,您不需要在多行字符串中包含這樣的部分的每個字符!您可以使用由包含文件中幾個字符的正則表達式組成的較短字符串;例如,.*正則表達式匹配任意數量的字符由位於其之前和之後的字符分隔。通過這種方式,您只需在搜索文本中包含足夠的部分,以使其在文件中具有唯一性。

rem Define the string to find 
set "find=<tree_node>!CR!!LF!" 
set "find=!find! <rule_name>bla</rule_name>!CR!!LF!" 
set "find=!find!.*!CR!!LF!" 
set "find=!find!.*!CR!!LF!" 
set "find=!find!</tree_node>" 
+0

感謝這個腳本,它可以工作,但只有短文本。當添加更長的文本時,我得到一個與findstr錯誤太長。 任何替代解決方案的幫助?例如PowerShell? 這個想法是修改一個.xml文件,在找到特定的標籤後插入新標籤(如上例)。 謝謝! – Nikec123

+0

請參閱我在答案中的編輯...我可以請您選擇這個作爲「最佳答案」,並且贊成嗎?謝謝! – Aacini