简体   繁体   English

内部循环查找和替换[批处理脚本]

[英]Find and Replace inside for loop [batch script]

The below code works, echo test.test 以下代码有效, echo test.test

set replaceWith=.
set str="test\test"
call set str=%%str:\=%replaceWith%%%
echo %str%

But, the below code echo ggg.hhhhh all the 4 times . 但是,下面的代码回显ggg.hhhhh全部4次

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%
)

What am I doing wrong here? 我在这做错了什么?

If you understand why your code uses call set str=%%str:\\=%replaceWith%%% , then you should be able to figure this out ;-) 如果您理解为什么您的代码使用call set str=%%str:\\=%replaceWith%%% ,那么您应该能够解决这个问题;-)

Syntax like %var% is expanded when the line is parsed, and your entire parenthesized FOR loop is parsed in one pass. 解析行时会扩展像%var%这样的语法,并且在一次传递中解析整个带括号的FOR循环。 So %replaceWith% and echo %str% will use the values that existed before you entered your loop. 因此, %replaceWith%echo %str%将使用您在进入循环之前存在的值。

The CALL statement goes through an extra level of parsing for each iteration, but that only partially solves the issue. CALL语句为每次迭代进行了额外的解析,但这只能部分解决问题。

The first time you ran the script, you probably just got "ECHO is on." 第一次运行脚本时,您可能只是“ECHO已开启”。 (or off) 4 times. (或关闭)4次。 However, the value of str was probably ggghhhhh and replaceWith was . 但是, str的值可能是ggghhhhhreplaceWith. after the script finished. 脚本完成后。 You don't have SETLOCAL, so when you run again, the values are now set before the loop starts. 您没有SETLOCAL,因此当您再次运行时,现在会在循环开始之前设置值。 After the second time you run you probably got ggghhhhh 4 times. 在你第二次运行之后,你可能会得到4次ggghhhhh And then from then on, every time you run the script you get ggg.hhhhh 4 times. 然后从那时起,每次运行脚本时,都会得到4次ggg.hhhhh

You could get your desired result by using CALL with your ECHO statement, and moving the assignment of replaceWith before the loop. 您可以通过将CALL与ECHO语句一起使用,并在循环之前移动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%%
)

But there is a better way - delayed expansion 但有更好的方法 - 推迟扩张

@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!
)

Please have a text book for Windows Command Shell Script Language and try this: 请有一本Windows Command 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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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