75

I have a directory for which I want to list all the .doc files with a ;.

I know the following batch command echos all the files:

for /r %%i In (*.doc) DO echo %%i

But now I want to put them all in a variable, add a ; in between and echo them all at once.
How can I do that?

set myvar="the list: "
for /r %%i In (*.doc) DO <what?>
echo %myvar%
Fortega
  • 19,463
  • 14
  • 75
  • 113

3 Answers3

65

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • 2
    Thanks a lot for this answer! It just solved me a problem creating dynamically a classpath into a batch file :) Adding the necessary modifications, but my problem was doing the concat and this has fixed it! – Charliemops Aug 30 '11 at 14:17
45

Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:

@echo off
setlocal enabledelayedexpansion
set myvar=the list: 
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%

Also consider the following restriction (MSDN):

The maximum individual environment variable size is 8192bytes.

devio
  • 36,858
  • 7
  • 80
  • 143
  • 1
    The restriction is wrong. The maximum environment variable size in Windows is around 64 KiB, so around 32k characters. In batch files, however, you have the problem that the maximum command-line length is 8190 characters, so every environment variable you set there must be shorter. Also, the 65 KiB total environment restriction is bogus. I just created environment variables totalling at a few MiB without problems. – Joey Jan 09 '10 at 10:32
  • 2
    The link says 65 THOUSAND KB, which would equal 64MB. I won't argue though, since I never dealt with it. – devio Jan 09 '10 at 14:49
  • 1
    So people don't make the same newbie mistake I did, remove "the list:" if you don't want that in your `myvar`. –  Mar 28 '13 at 15:15
0

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Pierre
  • 4,114
  • 2
  • 34
  • 39