Substring using bat command

There is the following in my bat file. they say

set path = c: \ temp \ test

so basically I want to get a result that will give me a result like c: \ temp \

I did not find any index equivalent in the bat command.

Thanks.

+7
substring batch-file
source share
4 answers

Background:

>set fullname=c:\mypath\oldfile >set changedname=%fullname:oldfile=newfile% >echo %changedname% c:\mypath\newfile 

In relation to the problem:

 > set fullname=c:\mypath\oldfile > set pathonly=%fullname:oldfile=% > echo %pathonly% c:\mypath\ 
+5
source share

The question that really makes me wish 4DOS still exists. However, I found something that might help in alt.msdos.batch.nt . The manual page for set seems to contain most of the same information. ( help set command)

 set test=123456789 rem extract chars 0-5 from the variable test set test=%test:~0,5% echo %test% 

(Note: tested on Windows XP SP3)

+1
source share

Why do you need this?

Johannes answer is a possible solution, but maybe the path you refer to is passed (or maybe) passed as a script argument, in which case you can use the following syntax:

 REM Extracts the drive and path from argument %1 SET p=%~dp1 

Alternatively, you can combine .. and the script path ( %0 ):

 REM Sets p to a sibling of the script directory SET p=%~dp0..\test 
+1
source share

Naive substrings have a problem that you have to tweak them every time your paths change, and this is not a general solution to the problem.

The following batch file provides proof of how you can do part of the path truncation:

 @echo off set foo=C:\Temp\Test call :strip echo %foo% goto :eof :strip if not "%foo:~-1%"=="\" ( set foo=%foo:~0,-1% goto :strip ) goto :eof 

It is hard-coded for one variable, but is easily fixed if necessary.

The main part here is the strip routine, which loops and truncates the last character of the string until a backslash is found. This effectively removes the last part of the path.

0
source share

All Articles