Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the equivalent of dirname() in a batch file?

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?

like image 272
arathorn Avatar asked Apr 22 '09 16:04

arathorn


People also ask

What does %% mean in batch script?

%%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.

How do I find the path in CMD?

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.

What is GEQ in batch file?

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.

How do I find the location of a batch file?

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 ).


1 Answers

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 :-)

like image 181
Joey Avatar answered Oct 07 '22 01:10

Joey