0

I need to write a batch script which pleases a user about filenames.

For example, a user launches the .bat file, selects option "delete files", the script waits for filenames and next the user writes it in one line like file1.txt file2.txt file3.txt file4.txt.

How can I grab the filenames like array elements to use it later?

deem
  • 1,844
  • 4
  • 20
  • 36

2 Answers2

1
setlocal EnableDelayedExpansion

:deleteFiles
set /P "filenames=Enter file names to delete: "

rem Grab filenames in an array
set n=0
for %%a in (%filenames%) do (
   set /A n+=1
   set "filename[!n!]=%%~a"
)

rem For example, to process the filenames:
for /L %%i in (1,1,%n%) do (
   echo %%i- !filename[%%i]!
)

The list of filenames must be separated by spaces (or commas, or semicolons); if a name include spaces, it must be enclosed in quotes.

For further information about arrays, see this post.

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Your answer is correct, but when I add some more lines to the code, your script doesn't work anymore. It looks the filename array is empty. My code is here if you want to have a look on it http://pastebin.com/UF0H9V3k – deem Sep 14 '13 at 16:46
1

version without delayed expansion:

@ECHO OFF &SETLOCAL
set "filepattern=*.txt"
for /f "tokens=1*delims=:" %%a in ('dir /b /a-d "%filepattern%"^|findstr /n $') do (
   set "filename[%%a]=%%~b"
)

for /f "tokens=2delims==" %%a in ('set "filename"') do (
    echo "%%~a"
)
Endoro
  • 37,015
  • 8
  • 50
  • 63