Reputation: 3688
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?
Upvotes: 2
Views: 1452
Reputation: 41287
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
Upvotes: 1
Reputation: 11367
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
Upvotes: 1
Reputation: 4750
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
Upvotes: 0