How do I exclude something from showing up with FindStr? - batch-file

I need to find multiple strings but the strings I look up flag for being in the batch itself. I search the string Incognito and the batch including it flags. How do I prevent this?
Edit: This is a snippet of my current code. Basically it opens the text file and shows this batch file in it and other stuff too which is good, but I need it not to flag this batch file.
findstr /i /s /m "Obligatory" *.* > str-unfixed.txt
if %errorlevel%==0 (
Call :TypeWriter "Obligatory Strings Found."
) else (
Call :TypeWriter "No Obligatory Strings Found."
)
start "" "C:\Users\%USERNAME%\Desktop\str-unfixed.txt"
Don't worry about the TypeWriter, this is only a snippet.
Edit2: Thanks for the edit Mofi, but it blanks out at console and doesn't complete.
Full script. Here we go.
#echo off
goto Next
::*************************************************************
:TypeWriter
echo(
(
echo strText=wscript.arguments(0^)
echo intTextLen = Len(strText^)
echo intPause = 30
echo For x = 1 to intTextLen
echo strTempText = Mid(strText,x,1^)
echo WScript.StdOut.Write strTempText
echo WScript.Sleep intPause
echo Next
)>%tmp%\%~n0.vbs
#cscript.EXE /noLogo "%tmp%\%~n0.vbs" "%~1"
echo(
exit /b
::**************************************************************
:Next
#echo off
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /i /s /m "Vape" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto VapeNoFileFound
for %%I in ("%OutputFile%") do if %%~zI == 1 goto VapeFileFound
:VapeFileFound
Call :TypeWriter "Vape Strings Found."
goto Kurium
:VapeNoFileFound
Call :TypeWriter "No Vape Strings Found."
goto Kurium
:Kurium
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /i /s /m "Kurium" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >>"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto KuriumNoFileFound
for %%I in ("%OutputFile%") do if %%~zI == 1 goto KuriumFileFound
:KuriumFileFound
Call :TypeWriter "Kurium Strings Found."
goto Spook
:KuriumNoFileFound
Call :TypeWriter "No Kurium Strings Found."
goto Spook
:Spook
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /i /s /m "Spook" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >>"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto SpookNoFileFound
for %%I in ("%OutputFile%") do if %%~zI == 1 goto SpookFileFound
:SpookFileFound
Call :TypeWriter "Spook Strings Found."
goto Aimassist
:SpookNoFileFound
Call :TypeWriter "No Spook Strings Found."
goto Aimassist
:Aimassist
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /i /s /m "Aimassist" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >>"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto AANoFileFound
for %%I in ("%OutputFile%") do if %%~zI == 1 goto AAFileFound
:AAFileFound
Call :TypeWriter "Aim Assist Strings Found."
goto Triggerbot
:AANoFileFound
Call :TypeWriter "No Aim Assist Strings Found."
goto Triggerbot
:Triggerbot
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /i /s /m "Triggerbot" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >>"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto TRNoFileFound
for %%I in ("%OutputFile%") do if %%~zI == 1 goto TRFileFound
cscript //nologo "C:\Users\%USERNAME%\Desktop\dedup.vbs" < "C:\Users\%USERNAME%\Desktop\str-unfixed.txt" > "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
del /s /q "C:\Users\%USERNAME%\Desktop\str-unfixed.txt" > nul
:TRFileFound
Call :TypeWriter "Triggerbot Strings Found."
start "" "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
:TRNoFileFound
Call :TypeWriter "No Triggerbot Strings Found."
start "" "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
pause > nul
::************************************************
And if you need dedup.vbs:
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set Dict = CreateObject("Scripting.Dictionary")
Do Until Inp.AtEndOfStream
On Error Resume Next
Line=Inp.readline
Dict.Add Line, ""
Loop
For Each thing in Dict.Keys()
Outp.writeline thing
Next
Edit3: Thanks Mofi!
My problem: need to get the items in the text document to show up on cmd window.
Script:
#echo off
goto Next
::*************************************************************
:TypeWriter
echo(
(
echo strText=wscript.arguments(0^)
echo intTextLen = Len(strText^)
echo intPause = 30
echo For x = 1 to intTextLen
echo strTempText = Mid(strText,x,1^)
echo WScript.StdOut.Write strTempText
echo WScript.Sleep intPause
echo Next
)>%tmp%\%~n0.vbs
#cscript.EXE /noLogo "%tmp%\%~n0.vbs" "%~1"
echo(
exit /b
::**************************************************************
:Next
#echo off
findstr /i /s /m /C:"Vape" /C:"Kurium" /C:"Spook" /C:"Aimassist" /C:"Triggerbot" /C:"Smoothaim" *.* > str-unfixed.txt
cscript //nologo "C:\Users\%USERNAME%\Desktop\dedup.vbs" < "C:\Users\%USERNAME%\Desktop\str-unfixed.txt" > "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
if %errorlevel%==0 (
Call :TypeWriter "Blacklisted Strings Found."
start "" "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
) else (
Call :TypeWriter "No Blacklisted Strings Found."
start "" "C:\Users\%USERNAME%\Desktop\str-fixed.txt"
)
pause > nul
::************************************************

The batch file could be filtered out for example with using this code:
#echo off
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
%SystemRoot%\System32\findstr.exe /I /M /S "Obligatory" *.* | %SystemRoot%\System32\findstr.exe /E /L /V /C:"%~nx0" >"%OutputFile%"
for %%I in ("%OutputFile%") do if %%~zI == 0 goto NoFileFound
call :TypeWriter "Obligatory strings found."
start "" "%OutputFile%"
set "OutputFile="
goto :EOF
:NoFileFound
del "%OutputFile%"
set "OutputFile="
call :TypeWriter "No obligatory string found."
goto :EOF
:TypeWriter
echo %~1
The output of first FINDSTR is filtered with a second FINDSTR which outputs all lines not ending with the name of the batch file searched as case-sensitive literal string.
The FOR command is used to check the file size of the output file.
Is the output file an empty file, i.e. the file size is equal 0 bytes, the string Obligatory was not found in any file except the batch file itself resulting in deleting the output file and printing the appropriate message.
Otherwise after printing the message that the string was found, the output file is opened in the application associated with file extension .txt.
The batch file above was tested for both scenarios on a subdirectory and not on entire drive C: as it can take a quite long time to finish on C:. There are hundred thousands of files on drive C: with dozens of GiB in total to search for the string when using *.* as file name pattern and start in root of drive C:.
EDIT 1: Define string to find in two parts
A much better solution as above is avoiding search string being in batch file. This can be done by using an environment variable for the string to find and define the value of the environment variable in two steps.
#echo off
setlocal
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
set "StringToFind=Obli"
set "StringToFind=%StringToFind%gatory"
%SystemRoot%\System32\findstr.exe /I /M /S "%StringToFind%" *.* >"%OutputFile%"
if errorlevel 1 (
del "%OutputFile%"
call :TypeWriter "No %StringToFind% strings found."
) else (
call :TypeWriter "%StringToFind% strings found."
start "" "%OutputFile%"
)
endlocal
goto :EOF
:TypeWriter
echo %~1
This batch file also searches for Obligatory, but it does not contain this string, just Obli and gatory.
EDIT 2: Define strings to find with omitted escape character
Here is one more solution where the multiple strings to find are assigned to environment variables with escape character ^ anywhere in the middle of the search strings to exclude the batch file.
^ is removed by Windows command interpreter on assigning the search strings to the environment variables as not being found within a double quoted string. Please note that this solution requires that the lines
set SearchX=S^earch String
do not have 1 or more trailing spaces/tabs as the trailing whitespace(s) would be also assigned to the environment variable. The search would not work anymore as expected with a not visible space or horizontal tab at end of those lines as being part of the search string.
Additionally this batch code outputs first each file name found by FINDSTR containing one of the 6 search strings to console window and next redirects the file name into the output text file.
#echo off
setlocal EnableExtensions
set "OutputFile=%USERPROFILE%\Desktop\str-unfixed.txt"
rem Define all search strings with omitted escape character.
set Search1=V^ape
set Search2=K^urium
set Search3=S^pook
set Search4=A^imassist
set Search5=T^riggerbot
set Search6=S^moothaim
rem Delete the output file from a previous run if existing at all.
del "%OutputFile%" 2>nul
for /F "delims=" %%I in ('%SystemRoot%\System32\findstr.exe /I /M /S /C:"%Search1%" /C:"%Search2%" /C:"%Search3%" /C:"%Search4%" /C:"%Search5%" /C:"%Search6%" *') do (
echo %%I
echo %%I>>"%OutputFile%"
)
if exist "%OutputFile%" (
call :TypeWriter "Obligatory strings found."
start "" "%OutputFile%"
) else (
call :TypeWriter "No obligatory string found."
)
endlocal
goto :EOF
:TypeWriter
echo %~1
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
del /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
rem /?
set /?
setlocal /?
start /?
See also the Microsoft support article Testing for a Specific Error Level in Batch Files and Microsoft TechNet article Using command redirection operators.

Just pipe the results through another check for the script name.
Replace your first line, findstr /i /s /m "Obligatory" *.* > str-unfixed.txt with this:
findstr/ism "Obligatory" *.*|findstr/ixvc:"%~nx0">str-unfixed.txt
I will add however that I would strongly suggest not searching through every single file on the C: drive looking for a specific search term. You really do need to filter this somehow perhaps by altering your file wildcard/mask.

Related

Log contents of text file before deleting

My script isn't logging the contents of run.txt to log.txt
I've tried to remove the delete command to see if it was deleting it too quickly and therefore couldn't log. But that wasn't the case.
What should I change?
#ECHO OFF &setlocal
SET File=run.txt
type %File%
for /f "tokens=*" %%A in (%File%) do (echo >> log.txt)
del "%File%" /s /f /q > nul
pause
Here is a very simple way to do the task you are requiring.
#echo off
REM Will only grab the first line of the file
set /p file=<run.txt
REM For the last line use a for loop
for /f "tokens=*" %%a in (%file%) do set last_line=%%a
(
echo %file%
)>>log.txt
del /f %file% >nul
If not %errorlevel% equ 0 (
ECHO ERROR - %errorlevel%
pause
exit /b
)
ECHO Success!
timeout /t 003
exit /b %errorlevel%
EXPLANATION
set /p is for set prompt. For more information you can use set /? in your CMD window or check out this site.
I wish I could speak more on what < does, but what it is doing here is piping the content of run.txt to our variable.
Then we echo out our variable to our log file with (ECHO This is our %file%)>>destination
>> is to append where > is to overwrite the file.
(
echo %file%
echo.
)>>%file%
Checking for an error is probably unnecessary, but I believe it is a good habit to build on which is what I am trying to do with that If not %errorlevel% statement.
No error? We Success and timeout ourselves for xxx seconds.
Try:
#ECHO OFF &setlocal
SET "File=run.txt"
type "%File%" >> "log.txt" && (del "%File%" /f > nul)
pause

feed command output into for /f

Is it possible to pipe the command output to the following batch file as its input?
I'd like to feed output from commands such as dir c:\temp |find "05" |find "new" to the following batch file. Because my command have many variations and I don't want to edit the batch file every time I need it, thus, I'm looking for a way to feed the command output directly to the batch file, instead of having the batch file generate its input using dir /b. Basically, what I'd like to achieve is to find from a list of files (generated using the dir command) the file whose name contains the highest number (achieved using the batch file.) Example:
today123.txt
today456.txt
tomorrow123.txt
tomorrow456.txt
With the dir command, I can filter off today or tomorrow, leaving only two files. Then, feed these two files to the batch file and have it select the one which has 456 in the file name. Of course, this is a simplified example. I may have more files and more groups than those in the example.
for /f %%a in ('dir /b ^|sort /r ^|findstr /r [0-9]') do (
set "filename=%%a"
goto done
)
:done
echo the highest found is %filename%
exit /b 0
There are quite a number of ways. This is one of them:
#echo off & set filename=
if "%~5" == "" set "myfind=dir /b ^| find "%~2" ^| find "%~3" ^| find "%~4" ^|sort /r ^|findstr /r [0-9]"
if "%~4" == "" set "myfind=dir /b ^| find "%~2" ^| find "%~3" ^|sort /r ^|findstr /r [0-9]"
if "%~3" == "" set "myfind=dir /b ^| find "%~2" ^|sort /r ^|findstr /r [0-9]"
if "%~2" == "" set "myfind=dir /b ^|sort /r ^|findstr /r [0-9]"
pushd "%~1"
for /f %%a in ('%myfind%') do (
set "filename=%%a"
goto done
)
:done
popd
if not defined filename echo Not match found & exit /b 1
echo the highest found is %filename%
exit /b 0
Typically you would run it as:
batch-file-name.cmd "C:\path\to\search" "search1" "search2" "search3"
for instance, using your example:
batch-file-name.cmd "c:\temp" "05" "new"
or even extend the search:
batch-file-name.cmd "c:\temp" "05" "new" ".txt"
How it works:
We set the search string each time in the case an additional find command is required. for now we have up to three finds and one path, but it can be extended to more. You have to set them in descending order though.
I also added an additional statement if not defined filename to ensure you are alerted if a find is not matched.
The following gets the highest of a given group:
#echo off
setlocal enabledelayedexpansion
set "search=today"
set "max=0"
for %%a in (%search%*.txt) do (
set "name=%%~na"
set "number=!name:%search%=!"
if !number! gtr !max! set /a max=number
)
echo max number for %search% is %max%
set "highest=%search%%max%.txt"
echo %highest%
Attention, there is no errorchecking at all, so it depends on the correct format of the file names. (errorchecking can be added when needed)
To get the search string as a parameter, simply replace set "search=today" with set "search=%~1"

How to search a string in a file?

I am writing a batch file to read all the files within the folder.
Below is my code:
#echo off
setlocal EnableDelayedExpansion
for %%I in (C:\test\*.print_job.*) do (
Set Name=%%~nxI
echo !Name!
)
pause
I am able to get all the .print_job files but now I want to read all the files and look for a specific identifier.
if the file contains "MOUNT" then move that file to C:\Folder1
if the file contains "PROD" then the file should get moved to
C:\Folder2
if the file contains "SPI" then the file should get moved to
C:\Folder3
Thanks in advance
#echo off
rem string target destination
call :movefiles "MOUNT" "C:\test\*.print_job.*" "C:\Folder1"
call :movefiles "PROD" "C:\test\*.print_job.*" "C:\Folder2"
call :movefiles "SPI" "C:\test\*.print_job.*" "C:\Folder3"
goto :eof
:movefiles
if not exist "%~3" md "%~3"
for /f "delims=" %%A in ('2^>nul findstr /l /m /c:"%~1" "%~2"') do (
move "%%~A" "%~3"
)
goto :eof
Use of call :movefiles to handle each of the 3 strings to
search for in the target files.
Call syntax: call :movefiles <string> <target> <destination>
Makes the destination directory if not exist. If string found
in a target file, the file will be moved into the destination
folder.
The findstr arguments used are:
/l Uses search strings literally.
/m Prints only the filename if a file contains a match.
/c:string Uses specified string as a literal search string.
You can insert rd "%~3" after the for loop if you want to
remove empty destination folders.
To loop every 2 seconds:
#echo off
:main
rem string target destination
call :movefiles "MOUNT" "C:\test\*.print_job.*" "C:\Folder1"
call :movefiles "PROD" "C:\test\*.print_job.*" "C:\Folder2"
call :movefiles "SPI" "C:\test\*.print_job.*" "C:\Folder3"
timeout /t 2 /nobreak >nul
goto :main
:movefiles
if not exist "%~3" md "%~3"
for /f "delims=" %%A in ('2^>nul findstr /l /m /c:"%~1" "%~2"') do (
echo move "%%~A" "%~3"
)
goto :eof
You may need to use Ctrl+C to end the script as it is in a continuous loop.
If you can use a task scheduler instead then that could work.
If a file name with the search word removed is different it had been in there.
#echo off
for %%I in (C:\test\*) do Call :Sub "%%I"
Pause
Goto :Eof
:Sub
Set "Name=%~nx1"
if "%Name%" neq "%Name:MOUNT=%" (move "%~1" "C:\Folder1\" & Goto :Eof)
if "%Name%" neq "%Name:PROD=%" (move "%~1" "C:\Folder2\" & Goto :Eof)
if "%Name%" neq "%Name:SPI=%" (move "%~1" "C:\Folder3\" & Goto :Eof)

Exclude certain file extensions from random file selection - batch script

I'm in the process of making a script that selects 25 random tracks from a user specified folder and adds them into an .m3u playlist. The trouble I have is that my music folders include various other files as well (eg: .txt, .jpg, .png, .nfo, etc...)
So I'm looking for a way of excluding the extensions listed above, limiting the script to just work with audio files. Any help would be much appreciated!
Here is the code so far... It has been stitched together from various sources so accept my apologies if it is a little crude:
#echo off
title Multiple Choice Menu
:home
cls
echo.
echo Select a genre:
echo =============
echo.
echo 1) Jungle
echo 2) D'n'B
echo 3) Reggae
echo 4) Hip-Hop
echo 5) Exit
echo.
set /p genre=Type option:
if "%genre%"=="1" cd /D "D:\NL Safe 2.0\High Quality\Jungle"
if "%genre%"=="2" cd /D "D:\NL Safe 2.0\High Quality\DnB\Standard DnB"
if "%genre%"=="3" cd /D "D:\NL Safe 2.0\High Quality\Reggae
if "%genre%"=="4" cd /D "D:\NL Safe 2.0\High Quality\Hip-Hop"
if "%genre%"=="5" exit
:: Clear existing Playlist
#echo. > C:\Users\Brew\Desktop\random.m3u
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"
:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N
:: Open 25 random files
for /l %%N in (1 1 25) do call :openRandomFile
:: Delete the temp file
del "%tempFile%"
:openRandomFile
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
'findstr "^%randomNum%:" "%tempFile%"'
) do (
setlocal EnableDelayedExpansion
set tune=%%B
#echo !tune! >> C:\Users\Brew\Desktop\random.m3u
)
Assuming your song's folder is on %1.
The dir command supports wildcards in the idea that
dir *.txt *.xml
will only list .txt and .xml files.
So you can try doing this instead:
...
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
pushd %1
dir /b /s /a-d *.mp3 *.EXT1 *.EXT2 | findstr /n "^" >"%tempFile%"
popd
...
Where EXT will be the extensions you want to match.
This will create your %tempFile% with only the files you want. Since the code that selects a file ramdomly works, as I see, over this file, it won't need to change at all.
I couldn't get dir to work with both target directory and wildcards.
Hope it helps.
This is why i used pushd and popd.
Thanks Daniel,
I had another go at it an finally got something working on my own. I used a series of If statements to put the random file through an extension validation check
This is the working script
#echo off
title Multiple Choice Menu
:home
cls
echo.
echo Select a task:
echo =============
echo.
echo 1) Jungle
echo 2) D'n'B
echo 3) Reggae
echo 4) Hip-Hop
echo 5) Exit
echo.
set /p genre=Type option:
if "%genre%"=="1" cd /D "D:\NL Safe 2.0\High Quality\Jungle"
if "%genre%"=="2" cd /D "D:\NL Safe 2.0\High Quality\DnB\Standard DnB"
if "%genre%"=="3" cd /D "D:\NL Safe 2.0\High Quality\Reggae
if "%genre%"=="4" cd /D "D:\NL Safe 2.0\High Quality\Hip-Hop"
if "%genre%"=="5" exit
:: Clear existing Playlist
#echo. > C:\Users\Brew\Desktop\random.m3u
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"
:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N
:openRandomFile
echo opening random file.....
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
'findstr "^%randomNum%:" "%tempFile%"'
) do (
setlocal EnableDelayedExpansion
set tune=%%B
FOR %%i IN ("!tune!") do call :CheckifMusic
)
:CheckifMusic
echo checking now
FOR %%i IN ("!tune!") DO (
SET fileextension=%%~xi
IF !fileextension!==.aif goto ResultTrue
IF !fileextension!==.flac goto ResultTrue
IF !fileextension!==.m4a goto ResultTrue
IF !fileextension!==.mp3 goto ResultTrue
IF !fileextension!==.wav goto ResultTrue
IF !fileextension!==.wma goto ResultTrue
echo fail
echo !fileextension!
goto openRandomFile
:ResultTrue
echo pass
echo !fileextension!
#echo !tune! >> C:\Users\Brew\Desktop\random.m3u
set /A COUNTER=COUNTER+1
IF !COUNTER!==25 (
echo finished
pause
goto Done
) ELSE (
goto openRandomFile
)
:Done
echo.
:: Delete the temp file
del "%tempFile%"
exit
)
pause
Probably not the cleanest way to do it, but hey - It works!
replace
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"
with
dir /b /s /a-d %1 | findstr /n /L /E /I /c:".mp3" /c:".wav">"%tempFile%"
Where the /c:".mp3"... can be extended as many times as you desire to select your target filetypes.
or
with
dir /b /s /a-d %1 | findstr /n /V /L /E /I /c:".jpg" /c:".txt">"%tempFile%"
Again repeating the /c:".jpg"... as many times as you desire to select your target exclude-me filetypes.
The /i means "case-insensitive", /e means "at the end of the line" /L means "literal match, not regex" and /v means "output non-matching"

findstr /m only returning 1st found filename

I am just starting to get my feet wet with MS Batch files. I have created a small batch that searches the entered directory for files containing a certain string using findstr /m. It is returning a file that contains the string, but only the first one it finds. I have searched the findstr /? and online command reference, as well as this site. I cannot find a way for findstr to return ALL the files with an instance of the string. What am I missing?
#echo off
setlocal
ECHO This Program Searches for words inside files!
:Search
set /P userin=Enter Search Term:
set /p userpath=Enter File Path:
FOR /F %%i in ('findstr /M /S /I /P /C:%userin% %userpath%\*.*') do SET finame=%%i
if "%finame%" == "" (set finame=No matching files found)
echo %finame%
set finame=
endlocal
:searchagain
set /p userin=Do you want to search for another file? (Y/N):
if /I "%userin%" == "Y" GOTO Search
if /I "%userin%" == "N" GOTO :EOF ELSE (
GOTO wronginput
)
Pause
:wronginput
ECHO You have selected a choice that is unavailable
GOTO searchagain
If you replace this:
FOR /F %%i in ('findstr /M /S /I /P /C:%userin% %userpath%\*.*') do SET finame=%%i
if "%finame%" == "" (set finame=No matching files found)
echo %finame%
set finame=
with this then it may work the way you expect
findstr /M /S /I /P /C:"%userin%" "%userpath%\*.*"
if errorlevel 1 echo No matching files found
Thanks everyone. Just in case someone else searches this site, here is my final code.
#echo off
ECHO This Program Searches for words inside files!
:Search
setlocal
set /P userin=Enter Search Term:
set /p userpath=Enter File Path:
findstr /M /S /I /P /C:%userin% %userpath%\*.* 2> NUL
if ERRORLEVEL 1 (ECHO No Matching Files found) ELSE (
GOTO searchagain
)
endlocal
:searchagain
setlocal
set /p userin=Do you want to search for another file? (Y/N):
if /I "%userin%" == "Y" GOTO Search
if /I "%userin%" == "N" GOTO :EOF ELSE (
GOTO wronginput
)
endlocal
:wronginput
ECHO You have selected a choice that is unavailable
GOTO searchagain
In your for loop, when you assign to finame the value of %%i, you are replacing the previous value, so only the last file gets echoed to console.
If you try your findstr command (out of the for) you will see the list of files.
to place all in var:
setlocal enabledelayedexpansion
set nlm=^
set nl=^^^%nlm%%nlm%^%nlm%%nlm%
for %%i in ('dir %userpath% /b') do for /f %%a in ('type "%userpath%\%%i"^|find "%userin%" /i') do set out=!out!!nl!%%i

Resources