简体   繁体   中英

Batch file in Windows to replace string in all files

I have to replace the string xmlns="http://www.wnco.com/bookingevents/v2" with nothing in all files in a windows directory

Please help me in resolving this

You can do this using powershell wrapped up in a batch file. The following is an example:

@for %%I in (%1) do @call :FIXUP "%%~fI" %2
@goto EXIT

:FIXUP
@>tmp.ps1 echo.get-content %1 ^| foreach-object { $_ -replace %2,""} ^| set-content '%~1.fixed'
@set curdir=%~dp0
@set script=%curdir%tmp.ps1
@powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%script%'"
@del >NUL /q %1 && @ren %1.fixed %1
@exit /b 0

:EXIT

The powershell script is created on the fly here and expects to see ASCII files. If you use unicode, check the "-Encoding Unicode" option for the powershell command.

So given a sample xml file as shown below we can use fixup.cmd *.xml "xmlns=""http://www.wnco.com/bookingevents/v2""" to apply this match expression to all the xml files in the current directory. I tested this using the following in some files:

<?xml version=1.0 encoding="UTF-8"?>
<a xmlns="http://www.wnco.com/bookingevents/v2">
<b>Something</b>
</a>

Running this:

C:\temp\demo>dir
27/02/2014  10:33               116 a.xml
27/02/2014  10:33               116 b.xml
27/02/2014  10:33               116 c 1.xml
27/02/2014  10:59               354 fixup.cmd

C:\temp\demo>fixup *.xml "xmlns=""http://www.wnco.com/bookingevents/v2"""

C:\temp\demo>type "c 1.xml"
<?xml version=1.0 encoding="UTF-8"?>
<a >
<b>Something</b>
</a>

The main issue to be careful with is the quoting to handle spaces in filenames.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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