我正在尝试开发一个脚本,要求用户输入他/她想要和需要的替换数量。
我尝试了以下脚本,但它没有按预期工作。
我的意见
Hello i am brow fox
brow fox is cunning one.
the real fox is brow`
我想用棕色代替眉毛,用狡猾代替狡猾
@echo off
setlocal enabledelayedexpansion
set /p num_replacements="How many search-and-replace operations do you want to perform? "
for /l %%n in (1,1,%num_replacements%) do (
set /p "search%%n=Enter search string %%n: "
set /p "replace%%n=Enter replace string %%n: "
)
for %%f in (*.txt) do (
set "filename=%%f"
set "tempfile=!filename!.tmp"
(
for /f "usebackq delims=" %%i in ("!filename!") do (
set "line=%%i"
for /l %%n in (1,1,%num_replacements%) do (
set "search=!search%%n!"
set "replace=!replace%%n!"
set "line=!line:%search%=%replace%!"
)
if defined line echo !line!
) >> "!tempfile!"
)
move /y "!tempfile!" "!filename!"
)
echo Done.
pause
但是打印出来的结果不是预期的
line:=
line:=
line:=
请查收协助
你的问题是这一行:
set "line=!line:%search%=%replace%!"
search
和replace
在遇到外循环(for %%f
)时被替换为各自的值
由于内部循环更改了这些变量,因此需要使用
!search!
访问它们,但这会导致语法冲突,因为 cmd
将无法预料程序员的意思
set "line=!line:!search!=!replace!!"
所以,您只需调用一个子 shell
CALL SET "line=%%line:!search!=!replace!%%"