Search code examples
windowsfilesystemscmddircd

cd to a search result with dir in cmd


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?


Solution

  • 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"