If you need to write a DOS batch file that takes a file path as an input parameter and needs to do something to other files in the same directory as the input file then you’ll find there is no easy way to get the file’s directory name into a variable.
You could pass in the directory name as a separate parameter but that seems like cheating. I sometimes find answers to problems like these on Rob van der Woude’s scripting site or Google, but no luck this time.
I had to figure this one out from scratch. Here’s what I do. Let me know if you have a better (shorter) way of doing this.
- Output the result of running ‘dir’ on the file path into a temporary file.
- Loop through the lines in the temporary file, skipping the first three, and then taking the third token.
- Assign that token to a variable.
If all has worked the variable which I’ve called ‘thedirectory’ should now contain the file path.
I’ve tested this on Windows 7 and I’m guessing it will work on other versions of Windows, but I’ll make no promises.
Here is the code:
goto :skip_functions
:setDir
if not %thedirectory% == "" goto :EOF
set thedirectory=%1
goto :EOF
:getDirectory
del %TEMP%\getdir.tmp
dir %1 > %TEMP%\getdir.tmp
for /f "skip=3 tokens=3" %%i in (%temp%\getdir.tmp) do call :setDir %%i
goto :EOF
:skip_functions
set thedirectory=""
call :getDirectory %1
@echo off
echo thefile =%1
echo thedirectory=%thedirectory%
And if you want to know what I needed it for have a look at my post about stitching together photos using ImageMagick.
There is a MUCH easier way to do this in Windows 2000 and later. Make use of the %~ modifiers (c.f.: HELP FOR on the DOS command line)
Here are a couple of examples:
FOR %%F in (%1) DO @ECHO %%~pF <– Batch file example
FOR %F IN (*.*) DO @ECHO %~pF <– Command line example
The ~p variable modifier, in this case, extracts the path from %%F. There are a number of these modifiers. Again, use HELP FOR from the command prompt to see them.