使用批处理脚本(batch file)逐行解析文本文件
Parsing the text file line-by-line using batch script (batch file)
所以,我在用批处理脚本编程时遇到了这个问题。以下代码将获取 yourwords.txt 文件并解析它。 existedWord
变量将包含文本文件的最后一个单词。所以,每次当我 运行 这个程序时,它只会将用户的输入与文本文件中的最后一个词进行比较,但我希望它从头开始进行比较,如果该词存在于文本文件中,则只显示消息作为 "Repeated word"。如果该词不在文本文件中,则将其添加到 .txt 文件并显示消息 "That is a new word."
.txt 文件每行包含单词。例如,
apple
banana
cat
dog
elephant
fish
gone
home
ignorant
注意:此文本文件中的字数可能有数百个。
我的目标是比较此文本文件中的每个单词,看看用户输入是否与 .txt 文件中存在的单词匹配。
@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
您不需要逐行解析文件。
@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
所以,我在用批处理脚本编程时遇到了这个问题。以下代码将获取 yourwords.txt 文件并解析它。 existedWord
变量将包含文本文件的最后一个单词。所以,每次当我 运行 这个程序时,它只会将用户的输入与文本文件中的最后一个词进行比较,但我希望它从头开始进行比较,如果该词存在于文本文件中,则只显示消息作为 "Repeated word"。如果该词不在文本文件中,则将其添加到 .txt 文件并显示消息 "That is a new word."
.txt 文件每行包含单词。例如,
apple
banana
cat
dog
elephant
fish
gone
home
ignorant
注意:此文本文件中的字数可能有数百个。
我的目标是比较此文本文件中的每个单词,看看用户输入是否与 .txt 文件中存在的单词匹配。
@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
您不需要逐行解析文件。
@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