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