Page 1 of 1

Searching via batch

Posted: 02 Oct 2020 03:02
by Hooby1
Hi

Within Windows I can use the search facility and I enter part of the filename I require and it shows a list of the location(s) of the file(s) (sometimes using the wildcard option if I don't know the full filename).

Is it possible to run a batch where it either prompts the user for part of the file name (I assume it can use wildcard search) and they enter the path of the folder they want to search and it then searches for all the filenames from the user input? Is it then possible to then output just the filename and a line of the path where that file is located to a textfile?

I have the following batch script but instead of hardcoding the filename, can it be changed so that the user is a) prompted what file name to search for (with wildcards) and b) Change the location of the path it is searching?

Code: Select all

@echo off
setlocal
rem change to the correct directory
cd /d C:\Temp
rem count the files
dir /b new*.* /s 2> nul | find "" /v /c > %temp%\count
set /p _count=<%temp%\count
rem cleanup
del %temp%\count
rem output the number of files
echo Number of Files found : %_count%
echo.
rem list the files
echo Files are located at :
echo.
dir /b new.txt /s
dir /b new.txt /s > OUTPUT.txt
endlocal
echo.
echo.
pause

Re: Searching via batch

Posted: 02 Oct 2020 10:55
by aGerman

Code: Select all

@echo off &setlocal
set "log=test.log"

set /p "spath=Enter the starting path: "
set /p "pattern=Enter the search pattern: "

>"%log%" (
  for /r "%spath%" %%i in ("%pattern%") do (
    echo %%~nxi
    echo %%~dpi
    echo(
  )
)

echo ~~~~~~~~~~~~~~
type "%log%"
pause
Example IO:

Code: Select all

Enter the starting path: C:\Program Files\Windows NT
Enter the search pattern: w*.exe
~~~~~~~~~~~~~~
wordpad.exe
C:\Program Files\Windows NT\Accessories\

Drücken Sie eine beliebige Taste . . .
Steffen

Re: Searching via batch

Posted: 03 Oct 2020 07:28
by Hooby1
Steffen

Amazing, this is exactly what I was trying to do.
However, is it possible to show a count of how many files have been found? First on the screen and then written to the log file?

Re: Searching via batch

Posted: 03 Oct 2020 07:42
by aGerman
Sure. Just increment a counter for each found file.

...

Code: Select all

set /a "count=0"
>"%log%" (
  for /r "%spath%" %%i in ("%pattern%") do (
    echo %%~nxi
    echo %%~dpi
    echo(
    set /a "count+=1"
  )
)
>>"%log%" echo total %count%
echo found files: %count%
...

Steffen

Re: Searching via batch

Posted: 03 Oct 2020 10:44
by Hooby1
Steffen

Brilliant, thanks for that.

Much appreciated :D