开发者

Batch file string manipulation

开发者 https://www.devze.com 2023-02-09 23:49 出处:网络
This is a very specific question, however; Say I have a batch file running from\\located in the directory c:\\data\\src\\branch_1

This is a very specific question, however;

Say I have a batch file running from\located in the directory c:\data\src\branch_1

How do I set my environment 开发者_StackOverflowvariable %buildpath% to c:\build\bin\branch_1 in a batch file?

(To be extra clear, if the same batch file is located in c:\foo\bar\branch_2 I want it to set %buildpath% to c:\build\bin\branch_2)


You should be able to use the environment variable %~dp0 to get you the drive and path of the batch file currently running. From there, it's a not-very-efficient method of stripping off the end of that string character by character and building a new string.

For example, the batch file:

@setlocal enableextensions enabledelayedexpansion
@echo off
set olddir=%~dp0
echo Current directory is: !olddir!
if "!olddir:~-1!" == "\" (
    set olddir=!olddir:~0,-1!
)
set lastbit=
:loop
if not "!olddir:~-1!" == "\" (
    set lastbit=!olddir:~-1!!lastbit!
    set olddir=!olddir:~0,-1!
    goto :loop
)
set newdir=c:\build\bin\!lastbit!
echo New directory is: !newdir!
endlocal

running as c:\data\src\branch1\qq.cmd returns the following:

Current directory is: C:\data\src\branch1\
New directory is: c:\build\bin\branch1

As to how it works, you can use !xyz:~n,m! for doing a substring of an environment variable, and negative m or n means from the end rather than the beginning. So the first if block strips off the trailing \ if it's there.

The loop is similar but it transfers characters from the end of the path to a new variable, up until the point where you find the \. So then you have the last bit of the path, and it's a simple matter to append that to your fixed new path.


Old case, but still...

easy way of setting current directory into variable.

@echo off
cd > dir.tmp
set /p directory= <dir.tmp
echo %directory%    <-- do whatever you want to the variable. I just did a echo..
del dir.tmp > nul
0

精彩评论

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