19

I am writing a batch script where if user input is empty or doesnot ends with "DTO" I need to ask user to enter DTO name again.

:INPUT
SET /P INPUTDTO=Enter the DTO:

IF "%INPUTDTO%"=="" (
      IF "%INPUTDTO%" ??????? (
             GOTO NODTO
      )
)

:NODTO
ECHO ERROR: Please enter a valid DTO.
GOTO INPUT

How to check if the user input ends with "DTO"

ams2705
  • 287
  • 2
  • 5
  • 17

4 Answers4

22

The existing INPUTDTO value should probably be cleared because SET /P will preserve the existing value if the user does not enter anything.

@echo off
set "INPUTDTO="
:INPUT
SET /P INPUTDTO=Enter the DTO:
if "%INPUTDTO:~-3%" neq "DTO" (
  ECHO ERROR: Please enter a valid DTO.
  goto INPUT
)

Add the /I switch to the IF statement if you want the comparison to be case insensitive.

dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Why are the quotes in `set "INPUTDTO="` needed? Thank you. – Sabuncu Jan 15 '15 at 12:49
  • 2
    @Sabuncu - when formatted like I have it, with the opening quote before the variable name, then any text after the last quote is ignored. It prevents inadvertent white space from being included in the assignment. Not necessary if the line ends where it should, but a good safe guard. – dbenham Jan 15 '15 at 13:12
1

The logic is simple, first remove any occurrences of "DTO" from your original string and store it into another variable. Then compare it with the original INTPUTDTO variable adding a "DTO" at the end.

:INPUT
SET /P INPUTDTO=Enter the DTO:
SET NEWINPUTDTO=%INPUTDTO:DTO=%

IF "%INPUTDTO%"=="" (
      IF NOT "%NEWINPUTDTO%DTO"=="%INPUTDTO%"  (
             GOTO NODTO
      )
)

:NODTO
ECHO ERROR: Please enter a valid DTO.
GOTO INPUT

Also, if you don't care about script complexity, then just use this:

IF NOT "%INPUTDTO:DTO=%DTO"=="%INPUTDTO%"
Sean Vaughn
  • 3,792
  • 1
  • 16
  • 14
1

If you are open to using other Software, you can use grep from GnuWin32. It will set you back 1.5MB

@echo off
:INPUT
SET /P INPUTDTO=Enter the DTO:


echo %INPUTDTO% | grep .*DTO\b

IF %ERRORLEVEL%==1 (
 goto NODTO
)
goto:eof
:NODTO
 ECHO ERROR: Please enter a valid DTO.
 GOTO INPUT
Midhat
  • 17,454
  • 22
  • 87
  • 114
0

Maybe you can use the substring-ing capabilities as described here:What is the best way to do a substring in a batch file?.

Then compare that substring agains "DTO".

Community
  • 1
  • 1
Anssssss
  • 3,087
  • 31
  • 40