Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of filenames in a directory and store that in a variable using cmd commands

Tags:

batch-file

I need to get all the filenames in a directory and store them in some variable from a command line.

I came across this

`dir /s /b > print.txt`

but this prints the file names to a txt file.

How can I store these names in a variable?

like image 499
user2907999 Avatar asked Oct 23 '13 11:10

user2907999


1 Answers

I'm assuming you really mean Windows batch file, not DOS.

Batch environment variables are limited to 8191 characters, so likely will not be able to fit all the file paths into one variable, depending on the number of files and the average file path length.

File names should be quoted in case they contain spaces.

Assuming they fit into one variable, you can use:

@echo off
setlocal disableDelayedExpansion
set "files="
for /r %%F in (*) do call set files=%%files%% "%%F"

The CALL statement is fairly slow. It is faster to use delayed expansion, but expansion of %%F will corrupt any value containing ! if delayed expansion is enabled. With a bit more work, you can have a fast and safe delayed expansion version.

@echo off
setlocal disableDelayedExpansion
set "files=."
for /r %%F in (*) do (
  setlocal enableDelayedExpansion
  for /f "delims=" %%A in ("!files!") do (
    endlocal
    set "files=%%A "%%F"
  )
)
(set files=%files:~2%)

If the file names do not fit into one variable, then you should resort to a pseudo array of values, one per file. In the script below, I use FINDSTR to prefix each line of DIR ouptut with a line number prefix. I use the line number as the index to the array.

@echo off
setlocal disableDelayedExpansion
:: Load the file path "array"
for /f "tokens=1* delims=:" %%A in ('dir /s /b^|findstr /n "^"') do (
  set "file.%%A=%%B"
  set "file.count=%%A"
)

:: Access the values
setlocal enableDelayedExpansion
for /l %%N in (1 1 %file.count%) do echo !file.%%N!
like image 186
dbenham Avatar answered Sep 21 '22 09:09

dbenham