Komak57
Komak57

Reputation: 113

Batch file giving File Not Found error

Been working on a systematic file search script to retrieve the name of all documents in a directory, and all sub directories that contain a determined search string. Essentially, it will log the search results. It would be nice to have it also search the file names, but that's not yet important.

Code:

@echo off
echo - Will search all files in current directory, and subdirectories.
echo - Will ignore case sensitivity.
echo - Will only search for term within readable documents.
set /p searchfilter=Search Filter: 
set results=%CD%\results.txt
echo Searching...
echo Results: > "%results%"
for /f "usebackq tokens=*" %%i in (`dir /s/b/A:-D/o:e`) do (
    find /i "%searchfilter%" "%%~nxi" >nul && echo %%~nxi >> "%results%"
)
echo Search complete.
pause

Run-down: System requests a string from the user. Then, the system saves a handle to the results file (thought that would fix the problem, didn't). The system then filters all files, excluding folders, from the directory, and sub directories, printing the bare name of the file (with extension), where it will proceed to scan each file for the search string, and save any positive search results to the text file.

It seems on a number of files, I receive a "File not found - " error, and need help identifying it. My guess, is that it has something to do with trying to find a sub directory file without the directory handle.

Upvotes: 0

Views: 7955

Answers (2)

foxidrive
foxidrive

Reputation: 41234

This should give you a tool to search filenames in the current folder tree and log the results to a file - in c:\path\file.ext format.

Replace searchstring with your search term and remove *.doc if you want to search all files, or replace it with *.doc *.txt *.ini *.src if you want to filter a number of filetypes.

@echo off
dir /b /s /a-d *.doc |findstr /r /i ".*\\.*searchstring.*" >results.txt

Upvotes: 0

Magoo
Magoo

Reputation: 80023

find /i "%searchfilter%" "%%i" >nul && echo %%~nxi >> "%results%"

should fix your problem, as you've flagged yourself. If you are searching for a file named fred.txt that exists in a subdirectory but mot in the root of the subtree scanned, then you'll get a File not found error.

Your choice whether you echo just the name and extension to results or whether you echo the full filename, of course. Personally, I'd use `%%i and get the whole thing.

I'd also change

for /f "usebackq tokens=*" %%i in (`dir /s/b/A:-D/o:e`) do (

to

for /f "delims=" %%i in ('dir /s/b/A:-D/o:e') do (

but that's just a matter of style in this case.

Upvotes: 1

Related Questions