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
2009-04-22 16:38:42
I think you mean, "put the *quotes* around the argument in the for loop:"
aphoria
2009-04-22 18:57:37
Yep, thanks. Can't think properly currently :)
Joey
2009-04-22 19:45:52
+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
2009-05-12 15:54:53