2

What's the simplest way in batch to get part of a path?

From other 'suggested questions' I'm now aware of ~dp0, but it seems like that only works on the current working directory?

I want to get a substring out of an environment variable, instead. Specifically, everything up to the final \.

In bash, I can do this with newpath=${fullpath%\\*}, is there an equivalently simple batch construct?

3
  • you need one or more for loops to get parent folders from %~dp0 Commented Jul 12, 2013 at 11:19
  • Am I mistaken in my understanding that ~dp0 gives output based on the current directory, then? Could you give a brief example of using it with a path stored as a variable? Commented Jul 12, 2013 at 11:35
  • ~dp0 returns the drive:path of the command line - so if you typed c:\bat\test.bat and the current directory was d:\backups then ~dp0 would return c:\bat Commented Jul 12, 2013 at 19:14

3 Answers 3

1

From how I read your question, you want the parent directory for the specified path.

Building on what RGuggisberg answered you can do something like this.

@echo off
call :Parent "%~dp0"
exit /b 0

:Parent <Path>
pushd "%~f1\.." || exit /b 1
echo %CD%
popd
exit /b 0
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a method to eliminate a trailing backslash from an environment variable:

@echo off
set "var=c:\program files\rock & roll\"
for /f "delims=" %%a in ("%var%\.") do echo set "var=%%~fa"
pause

1 Comment

Thanks for this suggestion. I actually wanted to remove rock & roll in this instance, not a trailing backslash, though looking at my Q again perhaps that wasn't clear enough :)
0

Below is one way to do it (assuming variable fullpath contains path). This works whether there is a trailing \ or not. Another way is to trim the last character, but that assumes you always have a trailing \, which you may not??? Of course you may want to store %cd% in some other variable instead of echoing it.

pushd %fullpath%
echo.%cd%
popd

3 Comments

@jam See the output of help set.
jam, %cd% is the current directory. You can find that on one of the multiple HELP pages for SET /? as suggested by Ansgar Wiechers.
@RGuggisberg, I tried your suggestion and it's giving me the full path (the final part of %fullpath% is a folder, not a filename, if that makes a difference?)

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.