How to concatenate strings in a Windows batch file?

WindowsBatch FileString Concatenation

Windows Problem Overview


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%

Windows Solutions


Solution 1 - Windows

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

Solution 2 - Windows

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.

Solution 3 - Windows

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFortegaView Question on Stackoverflow
Solution 1 - WindowsRubens FariasView Answer on Stackoverflow
Solution 2 - WindowsdevioView Answer on Stackoverflow
Solution 3 - WindowsPierreView Answer on Stackoverflow