Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable contains a letter/phrase in batch?

Tags:

batch-file

So I'm making, like, a fake messenger thing in batch to mess with people and I want to make it seem more realistic. Basically, I need to be able to search a variable to see if it contains a word? if that makes sense. Everyone that I've asked has said to use the findstr function, but I can't really do that because it's not a separate text file.

I was wondering if there was a way to do, like,

set /p input=thing (a variable for user input)
if %thing% contains "o" echo yes

I don't know if that makes sense. Sorry. I'm a beginner.

Thank you so much for reading this. I've been looking at stuff for this for like 3 hours

like image 602
catlin Avatar asked Dec 30 '25 11:12

catlin


1 Answers

findstr works, but you have to consider everything. For instance:

findstr /irc:"hi"

will find the word Hi any string, but it will also find high, which etc. So it will take a lot of time and effort to get the responses close to 100%.. anyway, all just for fun. Give this a try.

@echo off
cls
set /p "you=What is your name? "
@echo off & setlocal enabledelayedexpansion
set "cn=0"
for %%i in (Mary Catlin John Steve Emma Candice) do (
    set /a cn+=1
    set "name[!cn!]=%%i"
    echo !cn!. %%i
)
for /l %%a in (1,1,!cn!) do set "ucount=!ucount!%%a"
choice /c !ucount! /m "Hi %you%, Who'd you like to chat to?"
set name=!name[%errorlevel%]!
echo Please wait for !name! to join.. & timeout /t 6 /nobreak>nul 2>&1 & echo !name! is online.

for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
:chat
set /p "string=%you%: %ESC%[91m"
(timeout /t 1)>nul 2>&1
call :strings
goto :chat

:hi
echo %ESC%[92m!name!: What's up?%ESC%[0m
goto :eof

:doing
echo %ESC%[92m!name!: I am well, thank you%ESC%[0m
goto :eof

:time
echo %ESC%[92m!name!: It is now %time%%ESC%[0m
goto :eof

:date
echo %ESC%[92m!name!: The current date is %date%%ESC%[0m
goto :eof

:ben_jerry
echo %ESC%[92m!name!: I love Ben ^& Jerry's!!%ESC%[0m
goto :eof

:dude
echo %ESC%[92m!name!: DUDE!!%ESC%[0m
goto :eof

:not_love
echo %ESC%[92m!name!: WOAH!!! You're going to fast, I'm out%ESC%[0m
goto :eof

:strings
echo "%string%" | findstr /irc:"\<hi\>">nul 2>&1 && call :hi
echo "%string%" | findstr /irc:"\<how\>">nul 2>&1 && call :doing
echo "%string%" | findstr /irc:"\<time\>">nul 2>&1 && call :time
echo "%string%" | findstr /irc:"\<date\>">nul 2>&1 && call :date
echo "%string%" | findstr /irc:"\<love\>">nul 2>&1 && call :not_love
echo "%string%" | findstr /irc:"\<ben & jerry's\>">nul 2>&1 && call :ben_jerry
echo "%string%" | findstr /irc:"ice cream">nul 2>&1 && call :dude && call :ben_jerry
if "%string%" == "/exit" color & cls & exit
goto :eof

Result, where me: would be what I typed and `Bot: being the responses. enter image description here


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!