I am looking for a way in a Windows batch file to find if a file contains the word Shutdown
a given number of times.
I have tried this using FINDSTR
:
FINDSTR /r .*Shutdown.*{5} file.txt
This doesn't seem to work, but if I remove the {5}
it executes successfully.
Also I would eventually like the 5
to be a variable, presumably this is possible with some sort of dynamic command?
Thanks
.*Shutdown.*Shutdown.*Shutdown.*Shutdown.*Shutdown.*
would seem to be the only way for FINDSTR
srsly.
Test batch:
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%i IN (f5shutdown.txt) DO (
ECHO %%i|FINDSTR /r .*Shutdown.*Shutdown.*Shutdown.*Shutdown.*Shutdown.* >NUL
IF ERRORLEVEL 1 ECHO FAILED IN "%%i"
IF NOT ERRORLEVEL 1 ECHO FOUND IN "%%i"
)
GOTO :eof
Test textfile in f5shutdown.txt
Shutdown
Shutdown Shutdown
Shutdown Shutdown Shutdown Shutdown
Shutdown Shutdown Shutdown Shutdown Shutdown
Shutdown already !Shutdown Shutdown Shutdown Shutdown now
You should now Shutdown Shutdown Shutdown Shutdown Shutdown
ShutdownShutdownShutdownShutdownShutdown
OK, don't shutdown then...
Result:
FAILED IN "Shutdown"
FAILED IN "Shutdown Shutdown"
FAILED IN "Shutdown Shutdown Shutdown Shutdown"
FOUND IN "Shutdown Shutdown Shutdown Shutdown Shutdown"
FOUND IN "Shutdown already !Shutdown Shutdown Shutdown Shutdown now"
FOUND IN "You should now Shutdown Shutdown Shutdown Shutdown Shutdown"
FOUND IN "ShutdownShutdownShutdownShutdownShutdown"
FAILED IN "OK, don't shutdown then..."
Works for me (W7)
Ah - perhaps you meant "occurs on 5 (or whatever) lines or "occurs 5 times in the file"...
@ECHO OFF
SETLOCAL
FOR /f "delims=" %%i IN (f5shutdown.txt) DO (
ECHO %%i|FINDSTR /r .*Shutdown.*Shutdown.*Shutdown.*Shutdown.*Shutdown.* >NUL
IF ERRORLEVEL 1 ECHO FAILED IN "%%i"
IF NOT ERRORLEVEL 1 ECHO FOUND IN "%%i"
)
:: For 'shutdown' on n different lines: (assuming case-insensitive)
FOR /f %%i IN ('FIND /i /c "shutdown" ^<f5shutdown.txt') DO SET shutdowns=%%i
ECHO Second method: %shutdowns% lines found with "Shutdown"
:: For 'shutdown' occurrences (assuming case-insensitive)
SET /a shutdowns=0
FOR /f "delims=" %%i IN (f5shutdown.txt) DO (
SET line=%%i
CALL :findem
)
ECHO Third method found "Shutdown" %shutdowns% times
GOTO :eof
:findem
SET line=%line:"=%
SET after=%line:*shutdown=%
IF NOT DEFINED after SET /a shutdowns+=1&GOTO :EOF
if NOT "%line%"=="%after%" SET "line=%after%"&SET /a shutdowns+=1&GOTO findem
GOTO :eof
(I added an extra non-shutdown-containing line for the test. Found 8 lines and 28 occurrences)