Reputation: 1791
Hi I have full file path in a variable of batch file. How to get its first and second level parent directory path?
set path=C:\SecondParent\FirstParent\testfile.ini
Upvotes: 11
Views: 28428
Reputation: 1101
It is possible to get the file first parent (base dir) using a small subroutine that returns a ~dp
path to a file, :GetFileBaseDir
and :GetFileBaseDirWithoutEndSlash
in the example below.
Thank to @rojo for a way to achive the goal for multiple parents. I've enveloped his solution in a subroutine :GetDirParentN
to make it more useful.
@echo off
setlocal
REM Initial file path
set "pathTestFile=C:\SecondParent\FirstParent\testfile.ini"
echo pathTestFile: "%pathTestFile%"
REM First level parent (base dir)
REM with ending backslash
call :GetFileBaseDir dirFileBase "%pathTestFile%"
echo dirFileBase: "%dirFileBase%"
REM Same but without ending backslash
call :GetFileBaseDirWithoutEndSlash dirFileBaseWithBackSlash "%pathTestFile%"
echo dirFileBaseWithBackSlash: "%dirFileBaseWithBackSlash%"
echo.
REM Based on @rojo answer, using subroutine
REM One level up
call :GetDirParentN dirFileParent1 "%pathTestFile%" ".."
echo dirFileParent1: "%dirFileParent1%"
REM Two levels up
call :GetDirParentN dirFileParent2 "%pathTestFile%" "..\.."
echo dirFileParent2: "%dirFileParent2%"
REM Three levels up
call :GetDirParentN dirFileParent3 "%pathTestFile%" "..\..\.."
echo dirFileParent3: "%dirFileParent3%"
exit /b 0
:GetFileBaseDir
:: sets the value to dirFileBase variable
set "%~1=%~dp2"
exit /b 0
:GetFileBaseDirWithoutEndSlash
set "dirWithBackSlash=%~dp2"
REM substring from the start to the end minus 1 char from the end
set "%~1=%dirWithBackSlash:~0,-1%"
exit /b 0
:GetDirParentN
for %%I in ("%~2\%~3") do set "%~1=%%~fI"
exit /b 0
The output:
pathTestFile: "C:\SecondParent\FirstParent\testfile.ini"
dirFileBase: "C:\SecondParent\FirstParent\"
dirFileBaseWithBackSlash: "C:\SecondParent\FirstParent"
dirFileParent1: "C:\SecondParent\FirstParent"
dirFileParent2: "C:\SecondParent"
dirFileParent3: "C:\"
Upvotes: 1
Reputation: 24466
As npocmaka correctly suggests, pick a different variable from %PATH%
(or any of these other environment variables). Secondly, make sure your script uses setlocal
to avoid junking up your console session's environment with the variables in this script. Thirdly, just add a \..
for each ancestor you want to navigate. No need to bother with substring manipulation.
@echo off
setlocal
set "dir=C:\SecondParent\FirstParent\testfile.ini"
for %%I in ("%dir%\..\..") do set "grandparent=%%~fI"
echo %grandparent%
Upvotes: 9
Reputation: 57252
do not use variable PATH for this. %PATH% is a built-in variable used by the command prompt.
@echo off
set "_path=C:\SecondParent\FirstParent\testfile.ini"
for %%a in ("%_path%") do set "p_dir=%%~dpa"
echo %p_dir%
for %%a in (%p_dir:~0,-1%) do set "p2_dir=%%~dpa"
echo %p2_dir%
Upvotes: 20