How to get a Part of the Directory path in a batch file

跟風遠走 提交于 2020-01-11 03:13:07

问题


I have a BAT file in a directory

D:\dir1\dir2\getpath.bat

when i run the bat with the below code it prints

D:\dir1\dir2\

i want only the path D:\dir1\

The directory structure is not fixed , need the complete directory path other than the current directory in which BAT file resides.

@echo off
SET SUBDIR=%~dp0
ECHO %SUBDIR% 

tried using delims in a for loop but it didnt help.


回答1:


If it's the parent directory of the directory your script resides in you want, then try this:

@echo off
SET batchdir=%~dp0
cd /D "%batchdir%.."
echo %CD%
cd "%batchdir%"

(untested, please comment if there are problems)

Note that this will, of course, change nothing if your batch resides in your drive root (as in F:\) ;) If you'd like a special output if that's the case, you should test %CD% against %batchdir% before the echo.

EDIT: Applied patch, see comment by @RichardA




回答2:


@echo off
setlocal
SET SUBDIR=%~dp0
call :parentfolder %SUBDIR:~0,-1% 
endlocal
goto :eof

:parentfolder
echo %~dp1
goto :eof



回答3:


@echo off
SET MYDIR=%cd%
cd %MYDIR%\..
SET MYPARENTDIR=%cd%
cd %MYDIR%



回答4:


A single line of code does it :-)

If you want the trailing back slash, then

for %%A in ("%~dp0.") do @echo %%~dpA


If you don't want the trailing back slash, then

for %%A in ("%~dp0..") do @echo %%~fA



回答5:


%~dp0 returns the full drive letter and path of the current batch file. This can be used in a FOR command to obtain portions of the path:

When run from C:\dir1\dir2\dir3\batch.bat

FOR %%V IN ("%~dp0..\") DO @ECHO %%~dpV

returns C:\dir1\dir2\

This can be extended to continue higher up the path:

FOR %%V IN ("%~dp0..\..\") DO @ECHO %%~dpV

returns C:\dir1\

Source: Microsoft info on batch parameters




回答6:


You almost had it right. Using %~dp0 grabs the Drive+Full path to your .bat so it will return the folder which your bat file is located in as well.

Since the active directly will be the directory your bat is run from, all you'll need to do is:

@echo off
CD ..
SET SUBDIR=%CD%
ECHO %SUBDIR%

If putting this in a bat script to verify, throw in a PAUSE on a newline to see your output.



来源:https://stackoverflow.com/questions/7527529/how-to-get-a-part-of-the-directory-path-in-a-batch-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!