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 other words, the equivalent of dirname()
functionality in a typical UNIX environment. Is this possible?
%%i is simply the loop variable. This is explained in the documentation for the for command, which you can get by typing for /? at the command prompt.
Go to the destination folder and click on the path (highlights in blue). type cmd. Command prompt opens with the path set to your current folder.
GEQ is a 'Greater Than or Equal To' comparison operator for the IF command. Example. C:\> If 25 GEQ 50 ECHO smaller. C:\> If "5" GEQ "444" ECHO smaller.
You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch. bat ). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\ ) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch. cmd ).
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With