0
votes

I'm trying to assign subdirectory names to variables using FOR by saving CHDIR results to a temporary text document using a batch file

Batch file Input:

CD /d pathname
DIR /b /d >temp.txt
FINDSTR /b /n string pathname\temp.txt
ECHO find string results above
PAUSE
FOR /F "tokens=1-3" %%A IN ('FINDSTR /b string pathname\temp.txt') DO (
SET One=%%A
SET Two=%%B
SET Three=%%C
)
ECHO %One%
ECHO %Two%
ECHO %Three%
PAUSE

Command prompt output:

directory1
directory2
directory3
find string results above
Press any key to continue . . .
directory3
Echo is off.
Echo is off.
Press any key to continue . . .

The results from the initial FINDSTR should match the ECHO'd variables if they were assigned properly but only the final subdirectory name is being captured and the last two variables are not assigned.

how do I get each subdirectory to assign to a separate variable? Is there an easier way to accomplish this goal?

2

2 Answers

0
votes

The tokens clause is used to split each input line, not to determine the number of lines to read.

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Clean variables
    for %%b in (one two three) do set "%%b="

    rem Read folders
    for /d %%a in ("c:\somewhere\*") do (
        rem For each folder found, assign to a non assigned variable
        set "done="
        for %%b in (one two three) do if not defined done if not defined %%b (
            set "%%b=%%a"
            set "done=1"
        )
    )

    echo %one%
    echo %two%
    echo %three%
0
votes

The usual way to store and process an undefined number of items is via an array that is a variable with one name, but with several elements that are selected via a numeric index or subscript enclosed in square brackets; for example: set array[1]=Element number 1.

@echo off
setlocal EnableDelayedExpansion

rem Initialize the index
set index=0

rem Process all folders
cd /D pathname
for /D %%a in (string*) do (
   rem Increment the index to next element
   set /A index+=1
   rem Store the folder in next array element
   set "folder[!index!]=%%a"
)

rem Store the total number of folders
set number=%index%

rem Show the first folder
echo First folder: %folder[1]%

rem Show the last folder
echo Last folder: !folder[%number%]!

rem Show all folders
for /L %%i in (1,1,%number%) do echo %%i- !folder[%%i]!

This method requires Delayed Expansion, because the value of the index changes inside the for loop. If the index would be expanded this way: %index%, it would be expanded just one time before the for iterates. If the variable is enclosed in percents this way: !index! and Delayed Expansion is enabled (via the setlocal command at beginning), the value of index will be expanded each time the line is executed. You may read a further explanation on array management in Batch files here.