Jayasurya Satheesh
Jayasurya Satheesh

Reputation: 8033

Batch File : Read File Names from a Directory and Store in Array

I'm creating a batch file in which I need to list all the text file name of the specified folder then store and retrieve the same from an array. Is it possible in Batch Files? My current code to list the test files is as below

 dir *.txt /b

any help is much appreciated.

Upvotes: 7

Views: 48950

Answers (2)

user6250760
user6250760

Reputation:

Simulating Array

String is the only variable type in batch file. However, arrays can be simulated with several variables of identical name except a trailing numerical ID such as:

Array[1]    Array[2]    Array[3]    Array[4]     etc...

We can store each file name into these variables.


Retrieving command output

The first step is to put the command output into a variable. We may use the for /f loop.

for /f %%G in ('dir *.txt /b') do set filename=%%~G

The ('') clause and /f option specifies to collect the command output. Note that the filename you get is always the last one displayed because of variable-overwriting. This can be resolved by appending instead, but is beyond the scope of this answer.


Giving ID to files

In this case, I will name the array filename with a trailing ID [n], where n is a numerical ID.

setlocal enableDelayedExpansion
set /a ID=1

for /f "delims=" %%G in ('dir *.txt /b') do (
    set filename[!ID!]=%%~G
    set /a ID+=1
)

set filename
endlocal

Two things to note:

  • I have added "delims=" into the loop to ensure it works properly with default delimiters.

  • I replaced %ID% with !ID! because of delayed expansion. In short, when delayed expansion is disabled, the entire for loop is phrased before runtime, variables with new values are not updated block(()) structures; if enabled, the said variables are updated. !ID! indicates the need for update in each loop.

Upvotes: 13

Hackoo
Hackoo

Reputation: 18827

You can give a try for this batch file :

@echo off
Title Populate Array with filenames and show them
set "MasterFolder=%userprofile%\desktop"
Set LogFile=%~dpn0.txt
If exist "%LogFile%" Del "%LogFile%"
REM Iterates throw all text files on %MasterFolder% and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
echo     Please wait a while ... We populate the array with filesNames ...
SetLocal EnableDelayedexpansion
@FOR /f "delims=" %%f IN ('dir /b /s "%MasterFolder%\*.txt"') DO (
    set /a "idx+=1"
    set "FileName[!idx!]=%%~nxf"
    set "FilePath[!idx!]=%%~dpFf"
)

rem Display array elements
for /L %%i in (1,1,%idx%) do (
    echo [%%i] "!FileName[%%i]!"
    ( 
        echo( [%%i] "!FileName[%%i]!"
        echo Path : "!FilePath[%%i]!"
        echo ************************************
    )>> "%LogFile%"
)
ECHO(
ECHO Total text files(s) : !idx!
TimeOut /T 10 /nobreak>nul
Start "" "%LogFile%"

Upvotes: 2

Related Questions