0

Like the title says, I would like to know how to search a specified directory for a specified file using a for loop in a windows batch script. I can't use any 3rd party software.

Heres what I have at the moment:

for /R "%loc%" %%f in ("%searchterm%") do (
echo %%f
echo %%f>> "%genloc%wefound.txt"
)

%loc% is the location in which it should search.

%searchterm% is the file (e.g "hello.txt") that the script much search for.

It must output any files found (including their full path) on the screen and into the wefound.txt.

Let me know if you need more detail.

magicbennie
  • 423
  • 3
  • 8
  • 20

3 Answers3

1
for /f "delims=" %%f in ('dir /s /b /a-d "%loc%\%searchterm%"') do (
    echo %%f
    echo %%f>> "%genloc%wefound.txt"
)

To get the for /r command recursively enumerate the files under a starting point, the file set must include some wildcard character (* or ?). As you know the exact filename, let the dir command do the work of searching the file.

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • So, I tried that in my script. It works if the file(s) are in the sub-directories of the bat file itself. But if I set `%loc%` to C:\ it finds nothing at all. Any ideas? **EDIT:** I noticed I got this error: "The filename, directory name, or volume label syntax is incorrect." – magicbennie Apr 05 '14 at 08:18
  • 1
    @magicbennie, the code posted adds a backslash between the `%loc%` and `%searchterm%`. If the content of `%lock%` ends with a backslash it means the backslash is double, and if it is a subdirectory all works. But, if `%loc%` points to the root of a drive, the backslash can not be doubled. The best option is to ensure that `%loc%` will always include the backslash and remove the added one from the `dir` command. – MC ND Apr 05 '14 at 08:45
0
for /R "%loc%" %%f in ("%searchterm%") do (
   echo %%~Ff
   echo %%~Ff>> "%genloc%wefound.txt"
)

For further details, type: FOR /?

Aacini
  • 65,180
  • 12
  • 72
  • 108
0

Why complicate things with FOR? All you need is the DIR command:

dir /s /b /a-d "%loc%\%searchterm%>"%genloc%wefound.txt"&type "%genloc%wefound.txt"

The solution is even better if you can get your hands on a Windows port of the tee command (there are numerous free versions available). You could use my hybrid JScript/batch implementation of tee

dir /s /b /a-d "%loc%\%searchterm%"|tee "%genloc%wefound.txt"
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390