简体   繁体   中英

Get a part of the current path

I would like to get a part of the current directory where my batch script is from.

The location is something like this: Y:\abc\def\ghi\jkl\script.bat

I just want to keep what's after Y:\abc\def\ (that is \ghi\jkl)

How to do this?

I'm using the code below for getting the full path but how to make a delimitation?

for /f %%a in ("%CD%") do set CURR=%%a
echo %CURR%

Thank you for your precious help.

I believe that maybe you could put the section to be cut inside a txt file and then manipulate the string from the loop in the file, like this:

echo %cd% > path.txt

for /f "tokens=3,* delims=\" %%a in (path.txt) do echo %%b

Determining the depth with the argument tokens=3 with the delimiter character being "\" .

Based upon your stated "directory where my batch script is from", the following should suffice, (the last line is added for demonstration purposes, please change it as necessary) :

@Set "x=%~dp0"&SetLocal EnableDelayedExpansion
@Set "i=0"&Set "x!i!=%x:\="&Set /A i+=1&Set "x!i!=%"
@Set /A i-=1,y=i-1
@If %i% Lss 1 (Set "z=%x0%\")Else (If %i% Equ 1 (Set "z=%x0%\%x1%"
        )Else Set "z=!x%y%!\!x%i%!")
@EndLocal&Set "y=%z%"
@Echo %x% becomes %y%&Pause

I have made it so that if the scripts directory isn't deep enough, the full path will still be output.

If you want to use the current directory instead of the scripts location, change %~dp0 on line 1 to %__CD__% or %CD%\ as needed.

@echo off
setlocal

set "reversed="
set "fromdir=%~dp0"

for %%A in ("%fromdir:\=" "%") do call set "reversed=%%~A\%%reversed%%"
for /f "tokens=1-2 delims=\" %%A in ("%reversed%") do set "result=\%%B\%%A"

echo %result%
pause

If the path segments can be reversed, then getting the last 2 segments is a known number for setting the tokens option of 1-2 as they would become the 1st 2 segments. The 1st for loop does the reversing. The 2nd for loop gets the 1st 2 tokens and is set to result in reverse order, which is the original order.

The fromdir is set for the script directory %~dp0 , though it can be set with %cd% if is wanted.

View set /? for how "%fromdir:\=" "%" does replacement of \ with " " so that the path segments become individual arguments ie "C:\dir1\dir2\dir3" becomes "C:" "dir1" "dir2" "dir3" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM