【问题标题】:Parsing the text file line-by-line using batch script (batch file)使用批处理脚本(批处理文件)逐行解析文本文件
【发布时间】:2015-06-14 20:12:50
【问题描述】:

所以,我在批处理脚本中编程,我遇到了这个问题。以下代码将获取 yourwords.txt 文件并对其进行解析。 existedWord 变量将包含文本文件的最后一个单词。所以,每次我运行这个程序时,它只会将用户的输入与文本文件上的最后一个单词进行比较,但我希望它从头开始比较,如果该单词存在于文本文件中,则只显示消息为“重复单词”。如果该单词不在文本文件中,则将其添加到 .txt 文件并显示消息为“这是一个新单词。”

.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

【问题讨论】:

  • 有没有想过为此使用 find ? Find 可以忽略大小写,但它也会查找部分单词。因此,如果有人只输入“e”并且您使用 find 检查您的列表文件,它将在“apple”中找到“e”。但是,如果您不关心这是否是一种优雅的方式来做到这一点。

标签: windows batch-file scripting cmd


【解决方案1】:

你不需要逐行解析文件。

@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

【讨论】:

  • 哦,谢谢。这真的很好用。我不知道有一个 findstr 函数。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多