Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows 查找并替换内部for循环[批处理脚本]_Windows_For Loop_Batch File_Cmd_Pattern Matching - Fatal编程技术网

Windows 查找并替换内部for循环[批处理脚本]

Windows 查找并替换内部for循环[批处理脚本],windows,for-loop,batch-file,cmd,pattern-matching,Windows,For Loop,Batch File,Cmd,Pattern Matching,下面的代码起作用,echo test.test set replaceWith=. set str="test\test" call set str=%%str:\=%replaceWith%%% echo %str% 但是,下面的代码重复了4次ggg.hhhh SET SERVICE_LIST=(aaa\bbb ccc\dddd eeee\fffff ggg\hhhhh) for %%i in %SERVICE_LIST% do ( set replaceWith=. set str="%

下面的代码起作用,echo test.test

set replaceWith=.
set str="test\test"
call set str=%%str:\=%replaceWith%%%
echo %str%
但是,下面的代码重复了4次ggg.hhhh

SET SERVICE_LIST=(aaa\bbb ccc\dddd eeee\fffff ggg\hhhhh)

for %%i in %SERVICE_LIST% do (
set replaceWith=.
set str="%%i"
call set str=%%str:\=%replaceWith%%%
echo %str%
)

我做错了什么?

请准备一本适用于Windows命令Shell脚本语言的教科书,然后尝试以下操作:

@ECHO OFF &SETLOCAL
SET "SERVICE_LIST=(aaa\bbb ccc\dddd eeee\fffff ggg\hhhhh)"

for /f "delims=" %%i in ("%SERVICE_LIST%") do (
    set "replaceWith=."
    set "str=%%i"
    SETLOCAL ENABLEDELAYEDEXPANSION
    call set "str=%%str:\=!replaceWith!%%"
    echo !str!
    ENDLOCAL
)

如果您理解代码为什么使用
调用集str=%%str:\=%replaceWith%%
,那么您应该能够理解;-)

当解析行时,像
%var%
这样的语法会被扩展,整个括号中的FOR循环在一次过程中被解析。因此
%replaceWith%
echo%str%
将使用进入循环之前存在的值

CALL语句对每个迭代进行额外的解析,但这只能部分解决问题

第一次运行脚本时,您可能只收到4次“ECHO已打开”(或关闭)。然而,脚本完成后,
str
的值可能是
ggghhh
replaceWith
。您没有SETLOCAL,因此当您再次运行时,现在在循环开始之前设置值。第二次运行后,您可能会得到
ggghhh
4次。然后从那时起,每次运行脚本,您都会得到
ggg.hhhh
4次

通过在ECHO语句中使用CALL,并在循环之前移动replaceWith的赋值,可以获得所需的结果

@echo off
setlocal
SET SERVICE_LIST=(aaa\bbb ccc\dddd eeee\fffff ggg\hhhhh)
set "replaceWith=."
for %%i in %SERVICE_LIST% do (
  set str="%%i"
  call set str=%%str:\=%replaceWith%%%
  call echo %%str%%
)
但有一个更好的办法——推迟扩张

@echo off
setlocal enableDelayedExpansion
SET "SERVICE_LIST=aaa\bbb ccc\dddd eeee\fffff ggg\hhhhh"
set "replaceWith=."
for %%i in (%SERVICE_LIST%) do (
  set str="%%i"
  set str=!str:\=%replaceWith%!
  echo !str!
)