Use batch script to insert a string at a particular line in XML

穿精又带淫゛_ 提交于 2020-02-25 06:40:08

问题


i am new to programming. Can some1 kindly teach me how to insert a new line in an XML file using batch script? Current file has first 2 lines:

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:xxxxxxxxx

I want to add a format string on Line 2 so it has:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:xxxxxxxxxx

It has to be using batch-file as the rest of the file is built with it.

Cheers, Alan


回答1:


@echo off
    setlocal enableextensions disabledelayedexpansion
    set "secondLine=^<?mso-application progid="Excel.Sheet"?^>"
    (for /f "delims=" %%a in (input.xml) do (
        echo(%%a
        if defined secondLine ( 
            echo(%secondLine%
            set "secondLine="
        )
    )) > output.xml



回答2:


I assume you are on Windows. If you do not already have Unix Utils, I would recommend grabbing that first and adding it to your PATH.

You can then do

 sed "1 a <?mso-application progid=\"Excel.Sheet\"?>" Input.xml > Output.xml
 move Output.xml Input.xml

Note that the Windows version of sed may not support the -i option, but if it does, you can shorten this to

sed -i "1 a <?mso-application progid=\"Excel.Sheet\"?>" Input.xml


来源:https://stackoverflow.com/questions/22976323/use-batch-script-to-insert-a-string-at-a-particular-line-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!