How do I search for the directory of a file given its name using a batch script?

一笑奈何 提交于 2019-12-25 18:28:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!