I am trying to iterate through an semicolon-separated environment variable, such as PATH, CLASSPATH, INCLUDE, LIB, etc. This variable is given to the script as a command-line argument. I have already done this in Python, Perl, and Awk, and it's quite easy in those languages. However, I also tried to do it in cmd.exe language, like a masochist, without using any external commands. This is what I've come up with:
@echo off
setlocal EnableDelayedExpansion
if not "%1"=="" if not "%1"=="?" if not "%1"=="/?" if not "%1"=="-h" if not "%1"=="--help" if "%2"=="" goto :doit
echo Usage: %0 environment_variable
exit /b 1
:doit
for /f "tokens=1-25* delims=;" %%a in ("!%1!") do (
if not "%%a"=="" echo %%a
if not "%%b"=="" echo %%b
if not "%%c"=="" echo %%c
if not "%%d"=="" echo %%d
if not "%%e"=="" echo %%e
if not "%%f"=="" echo %%f
if not "%%g"=="" echo %%g
if not "%%h"=="" echo %%h
if not "%%i"=="" echo %%i
if not "%%j"=="" echo %%j
if not "%%k"=="" echo %%k
if not "%%l"=="" echo %%l
if not "%%m"=="" echo %%m
if not "%%n"=="" echo %%n
if not "%%o"=="" echo %%o
if not "%%p"=="" echo %%p
if not "%%q"=="" echo %%q
if not "%%r"=="" echo %%r
if not "%%s"=="" echo %%s
if not "%%t"=="" echo %%t
if not "%%u"=="" echo %%u
if not "%%v"=="" echo %%v
if not "%%w"=="" echo %%w
if not "%%x"=="" echo %%x
if not "%%y"=="" echo %%y
if not "%%z"=="" echo %%z
)
The problem is, how do I turn the long sequence into an iteration? I tried, but run into problems caused by the fact that many elements (between the semicolons) in the given variable contain spaces and/or quotation marks.
One possibility I've thought of was to use the substitution syntax:
%VAR:old=new%
But how can I replace the ';' character with the newline character?