Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Parent directory of a specific path in batch script

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
like image 828
selvakumar Avatar asked Jan 22 '16 08:01

selvakumar


2 Answers

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%
like image 53
npocmaka Avatar answered Sep 28 '22 00:09

npocmaka


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%
like image 22
rojo Avatar answered Sep 28 '22 00:09

rojo