Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace inside for loop [batch script]

The below code works, 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.

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?

like image 885
sElanthiraiyan Avatar asked Dec 16 '22 09:12

sElanthiraiyan


1 Answers

If you understand why your code uses call set str=%%str:\=%replaceWith%%%, then you should be able to figure this out ;-)

Syntax like %var% is expanded when the line is parsed, and your entire parenthesized FOR loop is parsed in one pass. So %replaceWith% and echo %str% will use the values that existed before you entered your loop.

The CALL statement goes through an extra level of parsing for each iteration, but that only partially solves the issue.

The first time you ran the script, you probably just got "ECHO is on." (or off) 4 times. However, the value of str was probably ggghhhhh and replaceWith was . after the script finished. You don't have SETLOCAL, so when you run again, the values are now set before the loop starts. After the second time you run you probably got ggghhhhh 4 times. And then from then on, every time you run the script you get ggg.hhhhh 4 times.

You could get your desired result by using CALL with your ECHO statement, and moving the assignment of replaceWith before the loop.

@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!
)
like image 54
dbenham Avatar answered Dec 23 '22 19:12

dbenham