I'm trying to split a string with the format: client_subfolder_filename
into three variable :
client
, subfolder
and filename
(which would include the extension too)
But I can't manage to test if the parsing failed (in which case the file is not a valid file and should be ignored)
I have tried ==""
, ==[]
, not defined
, not exist
, but nothing seems to work. Ideally, I would like to test if client
, subfolder
or fileName
is an empty string
Here is my script
@echo off
setlocal ENABLEDELAYEDEXPANSION
::mainDir is the directory where the customerfolders and the scripts are located
set mainDir=C:\Users\Me\Desktop\MyScript\src
cd %mainDir%
cd FilesToMove
set /a count=1
set client=""
set subfolder=""
set fileName=""
for %%i in (*) do (
echo !count! %%i
set /a count=count+1
for /F "tokens=1,2,3 delims=_" %%a in ("%%i") do (
set client=%%a
set subfolder=%%b
set fileName=%%c
if "!subfolder!" == "" goto NEXT
if "!fileName!" == "" goto NEXT
if not exist "%mainDir%\!client!\!subfolder!\" (mkdir "%mainDir%\!client!\!subfolder!")
move %%i "%mainDir%"\!client!\!subfolder!\!fileName!"
:NEXT
)
)
You can't use a GOTO inside a FOR command. It breaks out of the FOR command. That is your main problem. Regardless of that, why bother using delayed expansion. Just use the FOR variables directly with all your other commands. Also, DO NOT do this: set client=""
. You are assigning quotes to the variable. If you want to make it undefined then do this: set "client="
.
To test for %%b
and %%c
being empty use both of them at the same time in an IF
command. Reverse the sequence on one side. When they are not equal, then you know both of them are populated.
Here is how I would code your script.
@echo off
setlocal ENABLEDELAYEDEXPANSION
REM mainDir is the directory where the customerfolders and the scripts are located
set mainDir=C:\Users\Me\Desktop\MyScript\src
cd %mainDir%
cd FilesToMove
set /a count=0
for %%i in (*) do (
set /a count+=1
echo !count! %%i
for /F "tokens=1,2,3 delims=_" %%a in ("%%i") do (
rem client=%%a
rem subfolder=%%b
rem fileName=%%c
if NOT "%%b%%c"=="%%c%%b" (
mkdir "%mainDir%\%%a\%%c" >nul 2>&1
move "%%~i" "%mainDir%\%%a\%%b\%%c"
)
)
)