0

So, I am programming in the batch script and I came across this issue. The following code will take yourwords.txt file and parse it. The existedWord variable will have the last word of the text file. So, everytime when I run this program it will only compare the user's input with the last word on the text file, but I want it to compare from the beginning and if that word exist in the text file then just display message as "Repeated word". If that word is not in the text file then add it to the .txt file and display message as "That is a new word."

The .txt file contain words per line. For example,

apple
banana
cat
dog
elephant
fish
gone
home
ignorant

NOTE: the number of words in this text file could be hundreds.

My goal is to compare the every word in this text file and see if the user input match with the words existed in .txt file.

@echo off

:START
cls
echo.
echo Enter a word:
set /p "cho=->"
for /F "tokens=*" %%A in (yourwords.txt) do (set existedWord=%%A) 
if /I %cho%==%existedWord% (goto REPEATEDWORD)
echo %cho% >> yourwords.txt
)

:SUCCESSFUL
echo.
echo  That is a new word.
Ping -n 5 Localhost >nul
goto START

:REPEATEDWORD
echo.
echo  Sorry! that word is repeated word.
echo.
pause
goto START
1
  • Ever thought of using find for this ? Find can ignore case, but it would find parts of words too. So if someone only enters "e" and you check your list file with find it will find the "e" in "apple". But if this no concern to you find is an elegant way to do this. Commented Jun 14, 2015 at 20:19

1 Answer 1

1

you don't need to parse the file line by line.

@echo off
:START
cls
echo.
set /p "cho=Enter a word: -> "
findstr /i "\<%cho%\>" yourwords.txt >nul 2>&1
if %errorlevel%==0 (
  echo.
  echo  Sorry! that word is repeated word.
  echo.
) else ( 
echo.
  echo  That is a new word.
  echo %cho%>>yourwords.txt
  Ping -n 5 Localhost >nul
)
goto START
Sign up to request clarification or add additional context in comments.

1 Comment

Oh thanks. That works really good. I didn't know that there was a findstr function. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.