Find file and return full path using a batch file
Solution 1
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
Solution 2
Do this: -
for /f "delims=" %%F in ('dir /b /s "C:\File.txt" 2^>nul') do set MyVariable=%%F
Assuming you are searching C
drive for File.txt
.
LabRat
Updated on July 29, 2020Comments
-
LabRat almost 4 years
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?
-
LabRat over 11 yearsI was more thinking along the lines of 'find acad.exe /b /s' however I cant get this into a text file or variable...
-
Bali C over 11 yearsWhat do you mean? The
dir
command would have to be run in afor
loop anyways, why not just run thefor
loop? -
Bali C over 11 yearsI have added another option in my answer to use a
dir
command, more similar to what you wanted :) -
tobi42 almost 8 yearsTBH i didn't really understand any of the two answers, but this one looked like it also works with wildcards (i do not know that the other one doesn't!) so it tried it and it worked.
-
phuclv about 6 yearslooping through all the files is not good, especially if the folder contains millions of files. Just use
dir /b /s filename
-
OneAdamTwelve about 3 yearsThis doesn't really do much of a search, you have to know the file and what directory it's in, which isn't what the OP asked for.