问题
I know the name of a file, but I don't know what directory it resides in. I need to find the directory.
Given the name of a file, how can I search for a directory that contains this file with a batch script?
回答1:
I am assuming you know which drive it is located on, let us say drive C:
If you just want to list all the locations where MYFILE.TXT exists, then
dir /b /a-d /s "c:\myfile.txt"
The above will include the file name in the output.
If you need to do something with the path, let us say ECHO the path, but it could be anything, then
for /r c:\ %%F in (myfile.txt) if exist "%%F" echo %%~dpF
The ~dp modifies the expansion of %%F to only include the drive and path, stripping the name and extension.
If run from the command line instead of from a batch file then change the double percents to single percents.
If you don't know what drive the file is on then you will have to run either solution on each drive that might contain the file.
来源:https://stackoverflow.com/questions/12932919/how-do-i-search-for-the-directory-of-a-file-given-its-name-using-a-batch-script