遍历fart.exe并用变量替换搜索和替换文本

时间:2018-10-24 23:02:49

标签: batch-file fart

我需要进行一些复杂的搜索和替换。我正在使用一个循环处理并执行fart.exe的批处理文件,并且试图将来自两个不同数组的字符串输入到“搜索”字段和“替换”字段中。

一切正常,除了设置最终变量无效外,它们作为空字符串插入命令中。如何将数组的值放入这些变量中?

请注意,我搜索ID而不是替换ID的原因是,这是我正在替换正确链接的验证的一部分。

我的代码:

setlocal EnableDelayedExpansion

set i=0
for /F %%a in (merchants.txt) do (
   set /A i+=1
   set merArray[!i!]=%%a
)

for /F %%b in (merchant-ids.txt) do (
   set /A i+=1
   set idArray[!i!]=%%b
)

set n=%i%

for /L %%i in (0,1,%n%) do (
    set merDom=!merArray[%%i]!
    set merID=!idArray[%%i]!
    echo !merArray[%%i]!
    fart.exe -i -r "C:\css_js_test\*.css" http://%merDom%/merchant/%merId%/ http://www.example.com/merchant/%merId%/
)
pause

1 个答案:

答案 0 :(得分:1)

您的代码存在三个问题。 1)您需要在第二个FOR /F命令之前将计数器变量重置为零。 2)FOR /l命令必须从1开始。3)您需要对括号代码块内的所有变量使用延迟扩展。另外请注意,您可以直接通过fart命令使用数组变量,而不必将其分配给另一个环境变量。

@echo off
setlocal EnableDelayedExpansion

set i=0
for /F "delims=" %%a in (merchants.txt) do (
   set /A i+=1
   set merArray[!i!]=%%a
)

set i=0
for /F "delims=" %%b in (merchant-ids.txt) do (
   set /A i+=1
   set idArray[!i!]=%%b
)

set n=%i%

for /L %%i in (1,1,%n%) do (
    fart.exe -i -r "C:\css_js_test\*.css" http://!merArray[%%i]!/merchant/!idArray[%%i]!/ http://www.example.com/merchant/!idArray[%%i]!/
)
pause

为了向您展示此功能可用于我的测试,我仅使用一个名为input.txt的文件作为输入。我正在从命令提示符处运行所有内容,以便可以在运行批处理文件之前向您显示所有文件的内容。然后,最后显示更改后的输入文件的内容。

C:\BatchFiles\FART\SO>type merchant.bat
@echo off
setlocal EnableDelayedExpansion

set i=0
for /F "delims=" %%a in (merchants.txt) do (
   set /A i+=1
   set merArray[!i!]=%%a
)

set i=0
for /F "delims=" %%b in (merchant-ids.txt) do (
   set /A i+=1
   set idArray[!i!]=%%b
)

set n=%i%

for /L %%i in (1,1,%n%) do (
    fart.exe -i "input.txt" http://!merArray[%%i]!/merchant/!idArray[%%i]!/ http://www.example.com/merchant/!idArray[%%i]!/
)

C:\BatchFiles\FART\SO>type merchants.txt
www.ibm.com
www.target.com

C:\BatchFiles\FART\SO>type merchant-ids.txt
101010
202020

C:\BatchFiles\FART\SO>type input.txt
http://www.ibm.com/merchant/101010/
http://www.target.com/merchant/202020/

C:\BatchFiles\FART\SO>merchant.bat
input.txt
Replaced 1 occurence(s) in 1 file(s).
input.txt
Replaced 1 occurence(s) in 1 file(s).

C:\BatchFiles\FART\SO>type input.txt
http://www.example.com/merchant/101010/
http://www.example.com/merchant/202020/
相关问题