Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

windows - Find file and return full path using a batch file

Is it possible to create a batch file that searches for a file name, then returns its path so I can use it in a variable?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
for /r C:folder %%a in (*) do if "%%~nxa"=="file.txt" set p=%%~dpnxa
if defined p (
echo %p%
) else (
echo File not found
)

If the file you searched for was found it will set the variable %p% to the full path of the file including name and extension.

If you just want the path (as in the folder path without the file) then use set p=%%~dpa instead.

Note: If there is more than 1 file with the same name then the variable will be set to the last one found. Also the script after the for loop line isn't really necessary, just to show you if it found anything :)

If you want to do it using the dir command then use this, same rules apply

for /f "tokens=*" %%a in ('dir acad.exe /b /s') do set p=%%a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...