mentor交代的任务:
写个小公举,需要把一堆.zip中的各个文件夹中的xml文件的某些内容改成另一些。
代码如下:
echo off & color 0B
:: use the following instruction to delay the variable expansion. Also need to add !! around the variable.
setlocal enabledelayedexpansion
:: traverse all the zip files in the filer
for %%f in (*.zip) do (
echo %%f
mkdir aa
:: winrar x -o+ "%%f" "%~dp0\aa"
7z x "%%f" -o"%~dp0\aa"
cd /d aa\rta
:: get all the xml file in a zip
for /r %%i in (*.xml) do (
echo %%i
(for /F "usebackq delims=" %%a in ("%%i") do (
set anotherVariable=All Tenants
set "line=%%a"
if "!line!" equ " <xmlUsingTenantsIDs>System Default Tenant</xmlUsingTenantsIDs>" (
set "newLine= <xmlUsingTenantsIDs>!anotherVariable!</xmlUsingTenantsIDs>"
)else set "newLine=!line!"
echo !newLine!
)) > $
move $ "%%i"
)
cd /d %~dp0
:: get all the dir under the "aa",and update the corresponding zip file
7z u "%%f" .\aa\*
rd /s/q aa
)
echo ******SUCCESS******
pause
注意:
1.setlocal enabledelayedexpansion要放在代码最开始,否则变量的值不对。并且变量要用!!包起来。
2.对于for循环,参数/r代表一直遍历子文件夹。参数/f 要注意路径和文件内容中都不能有空格,否则只截取到空格。解决办法:在路径两边加“”,即使是变量也可以加,比如代码中的 “%%i”。
3.move命令可以代替ren和del等命令,只需要一行。