How do I find a Specific File Name in Batch and ch

2019-01-27 12:30发布

问题:

I am coding a batch file that will get the directory of a specific file(curl_for_64bit.exe). I tried using the find command but it does not work. It basically gets the directory of the file, changes to that directory so that it can be copied.

回答1:

you can traverse the directory tree with a FOR command checking for the existence of the required file until it's found

for /r /d %%a in (*) do (
  if exist %%a\curl_for_64bit.exe (
    pushd %%a
    goto :eof
  )
)


回答2:

you can use command like @Ken White say, then use other code to get the file's directory.

here is my code

rem you should go to the specific root directory(like c d e etc.)
cd /d c:\
dir /s /a /b curl_for_64bit.exe >tmp.txt                                                
set /P file_path=<tmp.txt                                                   
del tmp.txt

cd /d %file_path%\..

And if you just want to copy those files, why you want to go to the directory of file?



回答3:

The following script searches the file curl_for_64bit.exe in the directory tree rooted at C:\ROOT\ and changes to the parent directory where the found file is actually located:

for /F "delims=" %%F in ('dir /B /S /A:-D "C:\ROOT\curl_for_64bit.exe"') do (
    cd /D "%%~dpF"
)

Or this command line to be typed directly into cmd:

for /F "delims=" %F in ('dir /B /S /A:-D "C:\ROOT\curl_for_64bit.exe"') do @cd /D "%~dpF"

To learn what the ~dp modifier of the for variable %%F means and how it works, open a new command prompt window, type for /? and read the help text (see the last section in particular).