2

I have created a small batch file for windows, and I am having a small issue:

I defined a variable which contains a string, the path of a source file:

D:\git_repos\ALM_Sandboxs\Sensor_Config\StateManagement\ssm_state.cpp

I ´d like to extract the path without the file name:

D:\git_repos\ALM_Sandboxs\Sensor_Config\StateManagement\

Since the path can change, and so does the file name, I am having difficulties to do this. There are many ways, but I wasn´t able to use any of them:

The first one would be to count charaters of the file name:

set NumberOfCharacter

and do

set FilePath=%FilePathTemp2:~,%NumberOfCharacter%%

But this doesn´t work. I can only use number with this syntax: set FilePath=%FilePathTemp2:~,-18% ==> This works, but I´d like to read 18 from a variable

I have read that the batch interpreter can´t resolve the % pairs, so I tried

for /l %%x in (1,1,%strlength%) do set %FilePathTemp2%=%FilePathTemp2:~,-1%

It doesn´t work either, because the for loop seems not able to change FilePathTemp2 with a global scope.

I would be thankfull for any help

1 Answer 1

2
for %%a in (D:\git_repos\ALM_Sandboxs\Sensor_Config\StateManagement\ssm_state.cpp) do echo %%~dpa

(this is batch file syntax. To use it directly on command line, replace both %% with a single %)

The usage of modifiers (like %%~dpa) and which modifiers are possible is explained in for /?

Sign up to request clarification or add additional context in comments.

2 Comments

Hello Stephan, Thanks for the help! It worked, here is what I am using: :: remove file name from path (only folders), and go to path<br/> for %%a in (%FilePathTemp2%) do set FilePath=%%~dpa cd %FilePath%
@SebastienL You could simply get away without having to set the variable then cd to it. For instance, simply replace echo in Stepan's answer with cd So you will have for %%a in (D:\git_repos\ALM_Sandboxs\Sensor_Config\StateManagement\ssm_state.cpp) do cd %%~dpa you could also use pushd especially if you are changing dir to another drive. see pushd /? from cmdline for more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.