0

我正在尝试制作一个批处理文件来检查 xy.txt 中是否存在用户输入,这很容易

但现在如果用户输入是“hello world”,我想单独检查每个单词。

我试过了。。

@setlocal enableextensions enabledelayedexpansion
@echo off

:start
set /p word=" "

for /F "tokens=* delims= " %%A in ("%word%") do set A=%%A & set B=%%B 


if %A%=="" goto Anovalue
if not %A%=="" goto checkforA

:Anovalue
echo first word has no value
pause

 if %B%=="" goto Bnovalue
 if not %A%=="" goto checkforB

 :Bnovalue
 echo second word has no value
 pause
 goto start

 :checkforA
 findstr /c:"%A%" xy.txt > NUL
 if ERRORLEVEL 1 goto notexistA
 if ERRORLEVEL 2 goto existA

  :checkforB
  findstr /c:"%B%" xy.txt > NUL
  if ERRORLEVEL 1 goto notexistB
  if ERRORLEVEL 2 goto existB

  :existA
  echo first word does exist in xy.txt
  pause
  goto checkforB

  :existB
  echo second word does exist in xy.txt
  pause
  goto start

  :notexistA
  echo first word does not exist in xy.txt
  pause
  (echo %A%) >>xy.txt
  goto checkforB

 :notexistB
 echo second word does not exist in xy.txt
 pause
(echo %B%) >>xy.txt
goto start\

我不能以更简单、更聪明的方式做到这一点吗?

4

1 回答 1

0

有很多方法可以做你要求做的事情,其中​​许多使用的代码要少得多。例如,给定以下文件xy.txt

this is a test of the
system to see if it
will work the way
that i want it to
work today

此批处理文件 ( check.bat):

@echo off
setlocal ENABLEDELAYEDEXPANSION

set words=%1
set words=!words:"=!
for %%i in (!words!) do findstr /I /C:"%%i" xy.txt > NUL && echo     Found - %%i || echo Not Found - %%i

endlocal

那么返回以下内容:

c:\>check "is test smart"
    Found - is
    Found - test
Not Found - smart

但是,单词中的单词也将返回 true。例如,check "day"将找到day,即使它不是一个单独的词,因为它是 的一部分today。处理这种情况会有点棘手。为此,您需要用某个字符封装搜索词,然后用xy.txt相同的封装字符替换其中的所有空格。例如,如果我们使用 a ,将wh 中的.所有空格替换为,然后搜索,我们将只找到匹配的整个单词。xy.txt..word.

@echo off

setlocal ENABLEDELAYEDEXPANSION

set words=%1
set words=!words:"=!
set words=.!words: =. .!.

for /f "tokens=* delims=" %%i in (xy.txt) do (
  set line=%%i
  set line=.!line: =.!.
  echo !line!>>xy.txt.tmp
)

for %%i in (!words!) do (
  set word=%%i
  set word=!word:.=!
  findstr /I /C:"%%i" xy.txt.tmp > NUL && echo     Found - !word! || echo Not Found - !word!
)

del xy.txt.tmp

endlocal

我选择创建一个中间文件xy.txt.tmp来存放已编辑的文件,其中空格替换为.. 然后我们可以执行下面的命令,得到显示的结果:

c:\>check "this is a test of the stem today that will work each day"
    Found - this
    Found - is
    Found - a
    Found - test
    Found - of
    Found - the
Not Found - stem
    Found - today
    Found - that
    Found - will
    Found - work
Not Found - each
Not Found - day

它可以正确地在行首、行尾和中间的任何地方找到单词。唯一的缺点是它创建然后删除的中间文件。在没有中间文件的情况下这样做会有点复杂......

于 2013-11-08T22:16:15.093 回答