Search code examples
windowsbatch-filecommand-lineuser-inputsubstring

How to base conditional statements on existence of a variable substring


I'm writing a simple batch file to create new, user-defined files. My question is how to accept input for the extension with or without a period, and not yield a double-period (ie. name1..txt). I also want to avoid having to print instructions for them to include/not include it. Thanks for helping!

My approach is below. I want to look for a period at the beginning of the "extension" variable, ext, and run the appropriate FOR loop to create files.

setlocal enabledelayedexpansion
set num=
set name=
set ext=

:setnum
set /P "num=Number of files to create?: "
If not defined num Echo.&Echo You must enter a number to continue...&goto:setnum

:setname
set /P "name=Enter "root" name of file:"
If not defined name echo.&Echo You must enter the name of your new files to continue...&goto:setname

:setext
set /P "ext=What will be the file extension?:"
If not defined ext echo.&Echo You must enter an extension to continue...&goto:setext

pause
%ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot
%ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot

:extNoDot
for /L %%a in (1,1,%num%) do (echo %%a >> !name!%%a%ext%)
goto:eof

:extYesdot
for /L %%a in (1,1,%num%) do (echo %%a >> !name!%%a.%ext%)
goto:eof

:eof
EXIT /b

Solution

  • You don't actually state what's wrong with your current code. Without testing it, I can see that these two lines must be giving you problems:

    %ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot
    %ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot
    

    This is because you've got %ext:~0,1% at the beginning of a line as if it were a command. What you seem to be trying to do is pipe these to the FINDSTR command. Therefore you need to echo them:

    echo %ext:~0,1% | FINDSTR /R "[.]" && pause & goto:extNoDot
    echo %ext:~0,1% | FINDSTR /R "[.]" || pause & goto:extYesDot
    

    However, using an external command here is overkill. You should do the following instead:

    rem Remove any optional dot at the start
    if "%ext:~0,1%" == "." set "ext=%ext:~1%"
    

    And then just carry on as if ext never had a dot in the first place (no need for separate nodot and yesdot labels).