Reputation: 101
I want to loop though two directories A and B and where files with same names exist. And once I get path to both of the same name files I want to do some operation. Here is my batch script :
setlocal ENABLEDELAYEDEXPANSION
for /r "A" %%o in (*.c,*.cpp,*.h) do (
for /r "B" %%l in (*.c,*.cpp,*.h) do (
set x = %%~nxo
set y = %%~nxl
if %x% == %y% ( echo %x% )
)
)
endlocal
Here I am trying to print the names of the files but unable to do so. I am getting an error : echo was unexpected at this time. So what is the problem with this script.
Upvotes: 0
Views: 307
Reputation: 70923
The problem is spaces. Try this code
set x=something_1
set x = something_2
echo %x%
echo %x %
As you can see, placing a space after the name of the variable alters the name of the variable. You are assigning value to a variable with a space in its name, but try to retrieve the value from a variable without a space in its name.
Once spaces are solved, next problem: delayed expansion.
When execution reachs a block of code (in this case your two for
commands, the content enclosed in the parenthesis) and before the code gets executed, the content is parsed and in all places where variables are readed, variable references gets replaced with the value of variables.
The values they have before starting the execution of the block.
And then the block is executed the needed times (as stated in the for
command) without new substitutions, as now, there are no reads to variables in the code.
The value of the variables is changed (when the corresponding set
command is executed), but this changes are no reflected in the code executed. It contains no variables, they were replaced with their values.
The exception to this behaviour are the variables/replaceable parameters of the for
commands (%%o
and %%l
in your code) which are intended to change its value and, when delayed expansion is enabled (setlocal enabledelayedexpansion
) variables referenced as !var!
instead of the usual %var%
With this in mind, your code executes as it were written as
setlocal ENABLEDELAYEDEXPANSION
for /r "A" %%o in (*.c,*.cpp,*.h) do (
for /r "B" %%l in (*.c,*.cpp,*.h) do (
set x=%%~nxo
set y=%%~nxl
if == ( echo )
)
)
endlocal
There are no reads of the value of the variables. All has been changed with their initial values (in this sample, a emtpy value is assumed)
How to solve: two options
1 - No delayed expansion: use the variables of the for commands
for /r "A" %%o in (*.c,*.cpp,*.h) do for /r "B" %%l in (*.c,*.cpp,*.h) do (
if "%%~nxo"=="%%~nxl" ( echo "%%~nxo" )
)
2 - Delayed expansion enabled
for /r "A" %%o in (*.c,*.cpp,*.h) do for /r "B" %%l in (*.c,*.cpp,*.h) do (
set "x=%%~nxo"
set "y=%%~nxl"
if "!x!"=="!y!" ( echo "!x!" )
)
Upvotes: 2
Reputation: 41234
See what this provides for you:
@echo off
for /r "A" %%o in (*.c,*.cpp,*.h) do (
for /r "B" %%l in (*.c,*.cpp,*.h) do (
if "%%~nxo"=="%%~nxl" echo."%%~nxo"
)
)
Upvotes: 0