我正在尝试创建一个批处理文件,用于检查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\
我不能以更简单,更智能的方式做到这一点吗?
答案 0 :(得分: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
中的所有空格。例如,如果我们使用.
,则将xy.txt
中的所有空格替换为.
,然后搜索.word.
,我们将只找到匹配的整个单词。< / p>
@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
它正确地在行的开头,行的末尾以及其间的任何位置找到单词。唯一的缺点是它创建的中间文件然后删除。没有中间文件这样做会有点复杂......