Lote obtener el valor de la variable

Tengo el siguiente código:

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?

preguntado el 31 de julio de 12 a las 12:07

1 Respuestas

Tienes algunos problemas aquí:

  1. 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.

  2. You cannot set variables in a block and use them in the same block again without using delayed expansion. So you need

    setlocal enabledelayedexpansion
    

    al comienzo de su archivo por lotes y luego use !c! en lugar de %%c (which in itself is wrong already because variables of the %%x forma son for loop variables, not environment variables you set with set - pero %%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 analizado, 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
)

(También usé pushd/popd en lugar de cd to change directories which is a little nicer.)

Respondido 31 Jul 12, 13:07

It's right, spaces should be avoided, but set /a will remove the spaces itself, so set /a c=0 y set /a c = 0 son equivalentes - Jeb

Thank you so much. It works now. I am new to this, and I don't know all the rules yet. So thanks for explaining. - rocoso

jeb: Ok, I vaguely remembered as much, but imho it's best in this case to not let bad habits slip in and bite you later if you use a set sin /a :) - Joey

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.