15

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?

gunr2171
  • 10,315
  • 25
  • 52
  • 75
user2907999
  • 175
  • 1
  • 1
  • 5
  • Use `FOR` to put them into a variable. for /f %a in ('dir /s/b') do (echo %a) from the command line or double the %%'s if in a batch file. – Matt Williamson Oct 23 '13 at 11:22
  • 1
    Possible duplicate of [Batch file - Write list of files to variable](https://stackoverflow.com/questions/3238433/batch-file-write-list-of-files-to-variable) – Dave Jarvis Nov 28 '17 at 01:19

3 Answers3

22

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!
dbenham
  • 119,153
  • 25
  • 226
  • 353
  • EDIT - Ouch! Fixed a major bug in the 2nd solution (safe version) that no one had detected for two years! The safe aspect was broken until I used `%%A` in the assignment instead of `!file!`. – dbenham Oct 28 '15 at 10:55
5

As @Matt said, use a batch file.

setlocal enabledelayedexpansion
set params=
for /f "delims=" %%a in ('dir /s/b') do set params=!params! %%a 
Cookie Butter
  • 1,349
  • 12
  • 25
1
setlocal enableDelayedExpansion
set /a counter=0
for /f %%l in ('dir /b /s') do (
 set /a counter=counter+1
 set line_!counter!=%%l
)
set line_

If you want to store all in one variable check this: Explain how dos-batch newline variable hack works

Community
  • 1
  • 1
npocmaka
  • 51,748
  • 17
  • 123
  • 166