0

I want to know how to change to the directory containing a particular file name, using a batch file. First, I want to search for a particular file using the dir command. I know there will only be one file found. I then want to cd to the directory containing that file. Any suggestions?

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
Yerko Antonio
  • 657
  • 3
  • 8
  • 16

1 Answers1

2

This should work if you're only searching on the file name (edit: but only if the search uses a wildcard):

for /R %%i in ("myfile.*") do cd "%%~dpi"

(Replace %% with % if running from the command line rather than in a batch file.)

If the search doesn't use a wildcard, you could do this:

for /R %%i in (.) if exist "%%i\myfile.txt" do cd "%%i"

If you need to use the dir command because you want to, e.g., select only read-only files, this is another option:

for /F "usebackq tokens=*" %%i in (`dir /s /b /ar "readonly.txt"`) do cd "%%~dpi"
Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
  • Your 1st code will not work as written because the FOR will iterate a value for each subdirectory, regardless whether "myfile.txt" exists. You need to add `IF EXIST "%%i"` to the DO clause. – dbenham Nov 06 '12 at 00:54
  • @dbenham: ah, right. When I tested it I was using a wildcard, in that case it works. – Harry Johnston Nov 06 '12 at 01:25