How to make the batch file smarter

2019-08-16 10:41发布

问题:

I'm trying to make a batch file which checks if the user input does exist in xy.txt well thats easy

    @echo off 
    set /p input=" "

    findstr /c:"%word%" xy.txt > NUL
    if ERRORLEVEL 1 goto notexist
    if ERRORLEVEL 2 goto exist

    :exist
    echo user input does exist 
    pause > nul
    exit

    :notexist
    echo user input does not exist 
    pause > nul\

but now if the user input is "hello world" i want to check each word individually.

i tried this but it isn't good... and it saves if the word does not exist

    @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\

Couldn't I do that in a more easier and smarter way?

回答1:

@echo off

    setlocal enableextensions enabledelayedexpansion

    set words=
    set /p "words=What to search ? :"
    if not "%words%"=="" for %%w in ("%words: =" "%") do (
        findstr /c:%%w xy.txt > nul && set "_status=found" || set "_status=not found"
        echo %%w !_status!
    )

    endlocal