Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the user input ends with a specific string in batch (.bat) script

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"

like image 517
ams2705 Avatar asked Oct 03 '12 16:10

ams2705


People also ask

What does %% A mean in batch?

%%a refers to the name of the variable your for loop will write to. Quoted from for /? : FOR %variable IN (set) DO command [command-parameters] %variable Specifies a single letter replaceable parameter. (set) Specifies a set of one or more files. Wildcards may be used.

What does == mean in batch?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

How do you find if a file contains a given string using Windows command line?

You can run findstr from the command line or as a batch file. Open a new command line prompt by clicking on the Windows-key, typing cmd.exe, and selecting the result. Alternatively, use the Run command to open findstr.

What is %* in batch script?

%* expands to the complete list of arguments passed to the script. You typically use it when you want to call some other program or script and pass the same arguments that were passed to your script.


2 Answers

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.

like image 164
dbenham Avatar answered Oct 06 '22 10:10

dbenham


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
like image 23
Midhat Avatar answered Oct 06 '22 12:10

Midhat