Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch file to list folders that have a specific file in them

I'm trying to create a file that has a list of directories that have a specific file name in them.

Let's say I'm trying to find directories that have a file named *.joe in them. I initially tried just a simple dir /ad *.joe > dir_list.txt , but it searches the directory names for *.joe, so no go.

Then I concluded that a for loop was probably my best bet. I started with

for /d /r %a in ('dir *.joe /b') do @echo %a >> dir_list.txt

and it looked like it wasn't executing the dir command. I added the "usebackq", but that seems to only work for the /F command extension.

Ideas?

like image 550
Lee Avatar asked Apr 23 '10 17:04

Lee


3 Answers

Since "dir /s /b file_name" doesn't cut it, how about the following

for /d /r %a in (*) do  @if exist %a\*.scr (echo %a)

It would appear that inside a batch file the only thing that needs to be esaped is the %a giving

for /d /r %%a in (*) do  @if exist %%a\*.scr (echo %%a)
like image 91
torak Avatar answered Oct 29 '22 17:10

torak


This will print the directory and the file name, may or may not be helpful to you:

dir /b /s | findstr "\.joe"

findstr uses a regexp.

like image 35
Carlos Gutiérrez Avatar answered Oct 29 '22 15:10

Carlos Gutiérrez


Save this to search.bat or (something else you can remember)

@echo off
setlocal EnableDelayedExpansion
set last=?

if "%1" EQU "" goto usage

for /f %%I in ('dir /s /b /o:n /a-d "%1"') do (
  if !last! NEQ %%~dpI ( 
    set last=%%~dpI
    echo !last!
  )
)
goto end

:usage
echo Please give search parameter.

:end

and use as follows:

search.bat *.joe >dir_list.txt

Note that it searches within the current path context. You might want to add the .bat to a location that is in the PATH, so you can call it from any location.

like image 27
Tomalak Avatar answered Oct 29 '22 16:10

Tomalak