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?
You have a few problems here:
No spaces must be around the
=inset: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
at the start of your batch file and then use
!c!instead of%%c(which in itself is wrong already because variables of the%%xform areforloop variables, not environment variables you set withset– but%%pis correct because it is aforloop variable).Delayed expansion is necessary because
cmdwill expand variables to their values as soon as a statement is parsed, not directly prior to its execution. And the whole block of yourforloop is a single statement as far ascmdis concerned, thus when the loop runs any environment variables are already expanded to their values.So you’ll end with
(I also used
pushd/popdinstead ofcdto change directories which is a little nicer.)