Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...