I have a folder called newfolder
and there are abc.txt and def.txt inside of the folder. How can I store the file names abc.txt
and def.txt
into %file1% and %file2% using batch? The .cmd will be in the same directory as newfolder.
Asked
Active
Viewed 64 times
0

Ross Ridge
- 38,414
- 7
- 81
- 112

KenyKeny
- 121
- 1
- 3
- 19
2 Answers
1
If you wish to just assign the text abc.txt
and def.txt
to variables, use:
set file1=abc.txt
set file2=def.txt
But i assume from your question that you want to iterate through the file. If you explicitly wanted abc.txt
to be in the variable file1
and def.txt
to be in file2
use:
@echo off
for %%f in (*) do (
if %%f==abc.txt set file1=abc.txt
if %%f==def.txt set file2=file.txt
) else (
rem process other files
)
If you just want to assign each text file in the folder to a variable, i would recommend setting a counter and using that to set the file variables:
@echo off
setlocal EnableDelayedExpansion
set num=0
for /f %%f in ('dir /b /s') do (
set /a num+=1
set file!num!=%%f
)
rem now process it as you wish. example:
echo !file1!
echo !file2!
echo !file3!
echo !file4!
echo !file5!
echo !file6!
pause

UnknownOctopus
- 2,057
- 1
- 15
- 26
-
In `('dir /b /s')` , what does dir ,/b , /s means ?If i want to include the target folder, is it put in this way `('dir /b /s newfolder')`? – KenyKeny Jul 20 '15 at 05:44
-
`/s` includes sub directories and `/b` tells it to use bare format. And yes, you could add in a target folder. This code example was made to the specification that the batch file is in the same folder as the text files. If not, you could set the path like `('dir /b /s C:\Path\To\The\Folder\')` – UnknownOctopus Jul 20 '15 at 05:57
-
You have given a lot of options, i have no reason not to choose you. Thanks in advance. – KenyKeny Jul 20 '15 at 09:06
-
`set num=1 for /l %%x in(1,1,%%f) do ( set /p first_six=<% file%num% % echo first_six num+=1 pause )` what i want to do is to echo file1 first line,echo file2 first line, echo file3 first line ... iteratively. But i just can not use `%` properly to make use of variable in another variable ,Any ideas? Thanks – KenyKeny Jul 20 '15 at 09:15
-
Take a look [at this](http://stackoverflow.com/questions/9700256/bat-file-variable-contents-as-part-of-another-variable), it might answer your question. On another topic, if your following my 3rd example you need to use `!variable!` instead of `%variable%` when calling a variable (this is because i `setlocal EnableDelayedExpansion` – UnknownOctopus Jul 20 '15 at 15:00