I suggest to open first a command prompt window, run set /?
and read the output help. There is explained when and how delayed expansion must be used on an IF and a FOR example. The FOR example is nearly what you need.
So there could be used:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "CONTRAST="
rem Concatenate all lines in file test.txt in directory of the batch file
rem with using a semicolon as separator between the directory paths.
for /F "usebackq eol=| delims=" %%I in ("%~dp0test.txt") do set "CONTRAST=!CONTRAST!;%%~I"
rem Remove the semicolon at beginning of the list of directory paths.
if defined CONTRAST set "CONTRAST=!CONTRAST:~1!"
rem Do something with the environment variable CONTRAST.
rem There is just output the environment variable with its name as an example.
set CONTRAST
endlocal
This code works only if no directory name in the text file contains an exclamation mark.
Otherwise it would be necessary to use the following code:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "CONTRAST="
rem Concatenate all lines in file test.txt in directory of the batch file
rem with using a semicolon as separator between the directory paths.
for /F "usebackq eol=| delims=" %%I in ("%~dp0test.txt") do call :MergePaths "%%~I"
goto ProcessContrast
:MergePaths
set "CONTRAST=%CONTRAST%;%~1"
goto :EOF
:ProcessContrast
rem Remove the semicolon at beginning of the list of directory paths.
if defined CONTRAST set "CONTRAST=%CONTRAST:~1%"
rem Do something with the environment variable CONTRAST.
rem There is just output the environment variable with its name as an example.
set CONTRAST
endlocal
Please note following limitations:
- The first code is faster, but does not work for a directory path with one or more
!
in the path.
- A problem on further processing of
CONTRAST
is a directory path containing the separator ;
which is very unusual, but is in general possible.
- There is the command line argument length limit of 8192 characters which means that
"
left to environment variable name CONTRAST
plus the environment variable name CONTRAST
plus the equal sign plus the current length of the semicolon separated directory names plus "
at end of argument string to process by SET plus the string terminating null byte cannot be more than 8192 characters. In other words the list of ;
separated directory paths cannot be longer than 8180 characters.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
See also: Where does GOTO :EOF return to?