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"を検索します。その状況を処理するのは、もう少しトリッキーです。そのためには、検索語を何らかの文字でカプセル化し、すべてのスペースを同じカプセル化文字で置き換える必要があります。たとえば、a を使用し、 Wh 内のすべてのスペースを に置き換えてから を検索すると、一致する完全な単語のみが見つかります。daytodayxy.txt.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 に答える