views:

1593

answers:

2

I'd like to get the parent directory of a file from within a .bat file. So, given a variable set to "C:\MyDir\MyFile.txt", I'd like to get "C:\MyDir". In otherwords, the equivalent of dirname() functionality in a typical UNIX environment. Is this possible?

+7  A: 
for %%F in (%filename%) do set dirname=%%~dpF

This will set %dirname% to the drive and directory of the file name stored in %filename%.

Careful with filenames containing spaces, though. Either they have to be set with surrounding quotes:

set filename="C:\MyDir\MyFile with space.txt"

or you have to put the quotes around the argument in the for loop:

for %%F in ("%filename%") do set dirname=%%~dpF

Either method will work, both at the same time won't :-)

Joey
I think you mean, "put the *quotes* around the argument in the for loop:"
aphoria
Yep, thanks. Can't think properly currently :)
Joey
+2  A: 

If for whatever reason you can't use FOR (no Command Extensions etc) you might be able to get away with the ..\ hack:

set file=c:\dir\file.txt
set dir=%file%\..\
Anders