Tharsan Sivakumar
Tharsan Sivakumar

Reputation: 6531

Batch script - dynamic/variable paths in loop

My requirement is to write a batch script to find and replace the a string in all of the *-spec.js files in given set of directories. Hence I have written the batch file and running the batch script as below.

<script file name> <search_string> <replace_string> <folder_path_1> <folder_path_2> <folder_path_n>

(I am sure the folder_path_n will not go beyond 7)

e.g C:\CI\Scripts>replace.bat hello world C:\app\e2e C:\sppa\e2e So my script is as below.

@echo off
setlocal enabledelayedexpansion

set argCount=0
for %%x in (%*) do (
   set /A argCount+=1
   set "argVec[!argCount!]=%%~x"
)

set search=%1
set replace=%2

echo Search is %search%
echo Replace is %replace%

for /L %%i in (3,1,%argCount%) do (
   set path=!argVec[%%i]!
   echo path is !path!

   for /R !path! %%F in (*spec.js) do (
      echo %%F
   )
)

Here it prints the 4 arguments correctly even the path is also printed as expected. In the next step it's expected to loop through the given path and gets all of the files that ends with "spec.js".

e.g not working:

for /R !path! %%F in (*spec.js) do (
   echo %%F
)

But it prints nothing. Instead if the variable is replaced with hard coded value, it works as expected.

e.g - working:

for /R C:\app\sppa\e2e %%F in (*spec.js) do (
   echo %%F
)

Your help is highly appreciated!

Upvotes: 1

Views: 1349

Answers (2)

Tharsan Sivakumar
Tharsan Sivakumar

Reputation: 6531

I also tried similar as suggested by @Andre Kampling as below.

cd !path!
::echo Changed the path to !path!
FOR /R %%F IN (*spec.js) DO (
 echo %%F
)

Upvotes: 1

Andre Kampling
Andre Kampling

Reputation: 5631

The reason it's not working is that the variable content must be known when the loop is parsed means that it only works with variables that can be expanded without delayed expansion. Nevertheless there is an easy solution as a for /r loop is working with the current path (from ss64).

If the [drive:]path are not specified they will default to the current drive:path.

Just change directory to !path! and then go back:

rem Change into !path! and remember directory coming from
pushd !path!
for /R %%F in (*spec.js) do (
   echo %%F
)
rem Change back to origin
popd

Upvotes: 2

Related Questions