开发者

substring using bat command

I have the following thing in my bat file. say

set path=c:\temp\test

so basically i want to have an output which would give me the result as c:\temp\

i didnt find any indexof equivalent in bat command开发者_Python百科.

Thanks.


Background:

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

Applied to problem:

> set fullname=c:\mypath\oldfile
> set pathonly=%fullname:oldfile=%
> echo %pathonly%
c:\mypath\


A question that really makes me wish 4DOS still existed. 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. (command help set)

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)


Why do you want that?

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

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

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

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


Naïve substrings have the problem that you have to adjust them every time your paths change and it isn't a generic solution to the problem.

The following batch file gives a proof of concept how you might do the truncation part of the path:

@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's hard-coded to a single variable but that is easily fixed if needed.

The core part here is the strip subroutine which loops and cuts off the last character of the string until a backslash is found. This effectively removes the last part of the path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜