Reputation: 3509
I have the following code:
for /f "tokens=*" %%p in (input.txt) do (
echo %%p
cd %%p
set /a c = 0
for %%f in (*) do (
echo %%f
if not exist *test*.* (
set /a c += 1
)
)
if %%c GTR 0 echo %%p >>folders.txt
cd ..
)
But the last if statement is not working. I want to know what do I have to do to have access to the variable c that I set up in the first for. I've tried different combinations like !c! or %c% but nothing seems to work. What am I missing?
Upvotes: 0
Views: 1154
Reputation: 354386
You have a few problems here:
No spaces must be around the =
in set
:
set c=0
set /a c+=1
Otherwise you're creating a variable whose name ends in a space.
You cannot set variables in a block and use them in the same block again without using delayed expansion. So you need
setlocal enabledelayedexpansion
at the start of your batch file and then use !c!
instead of %%c
(which in itself is wrong already because variables of the %%x
form are for
loop variables, not environment variables you set with set
– but %%p
is correct because it is a for
loop variable).
Delayed expansion is necessary because cmd
will expand variables to their values as soon as a statement is parsed, not directly prior to its execution. And the whole block of your for
loop is a single statement as far as cmd
is concerned, thus when the loop runs any environment variables are already expanded to their values.
So you'll end with
setlocal enabledelayedexpansion
for /f "tokens=*" %%p in (input.txt) do (
echo %%p
pushd %%p
set /a c=0
for %%f in (*) do (
echo %%f
if not exist *test*.* (
set /a c+=1
)
)
if !c! GTR 0 echo %%p >>folders.txt
popd
)
(I also used pushd
/popd
instead of cd
to change directories which is a little nicer.)
Upvotes: 1