Chhandra Aadhikary
Chhandra Aadhikary

Reputation: 47

Parsing the text file line-by-line using batch script (batch file)

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

Upvotes: 0

Views: 7177

Answers (1)

Stephan
Stephan

Reputation: 56165

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

Upvotes: 1

Related Questions