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

前端 未结 3 932
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 14:45

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`


        
相关标签:
3条回答
  • 2020-12-16 14:58

    As @Matt said, use a batch file.

    setlocal enabledelayedexpansion
    set params=
    for /f "delims=" %%a in ('dir /s/b') do set params=!params! %%a 
    
    0 讨论(0)
  • 2020-12-16 15:11
    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

    0 讨论(0)
  • 2020-12-16 15:16

    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!
    
    0 讨论(0)
提交回复
热议问题