2

I've searched and found several examples on this, but I don't seem to get anything to work... I'm writing a simple Windows batch script to unzip files. In my batch script I have a variable, zipfile, that is dynamically assigned as the most recent Zip file in folder and subfolders:

for /f "tokens=*" %%a in ('dir d:\temp\*.zip /s /b /od') do set zipfile=%%a 

To simplify, considering the value:

set zipfile=d:\temp\mysubfolder\myfile.zip

How can I get the full path, "d:\temp\mysubfolder\" ? Thank you!

2 Answers 2

3

Easy:

for /f "tokens=*" %%a in ("%zipfile%") do (set fullpath=%%~dpa)
Echo %fullpath%

Done! Make sure %zipfile% does not have surrounding quotes.

Mona

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Got my %fullpath% variable as I needed to proceed.
@mahiro shorter with the same result: for %%a in ("%zipfile%") do set "fullpath=%%~dpa"
@Endoro But that doesn't include for spaces
Why do you think it doesn't handle spaces?
Wait whoops, I thought it was /f.
2

See the call /? for how to use labels inside a batch file. It also explains how to extract the drive, path, and filename from a parameter.

set zipfile=d:\temp\mysubfolder\myfile.zip
call :SETZIPPATH %zipfile%
goto:eof 

:SETZIPPATH
set zippath=%~dp1

You can also do the call from inside the for loop.

4 Comments

Thank you! Went with the line of code above for my batch script, but appreciate the tip! I didn't know about these labels for batch files before, so it's something I learned for a next time.
Great. I'm glad you learned something and I hope it makes it easier for you to batch something in the future.
+1 but a call is slower than for /f --> dostips.com/forum/viewtopic.php?p=10681
Is it though? I was able to run a crude test including 20 for loops vs. 20 label calls with echo %time% before and after. I understand that part of the measurement is the set command, but they are identical in both cases. It measured ~740ms for the for loop and ~670ms for the call. I am not convinced that a for loop is quicker than the local call. Again, I understand my measurement method is quite crude.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.