How do I get the name of the parent folder in a command prompt?
I'm in a Windows Command Line and want the parent folder in a variable.
Assuming current directory is "C:\foo\bar", how can I get the v开发者_开发百科alue "bar"?
I'm expecting something like a "find last backslash in CD and that's it".
And please, no powershell references; I want plain old Windows Command Line operations.
My solution uses substitution and works for root directory as well:
call set PARENT_DIR=%CD%
set PARENT_DIR=%PARENT_DIR:\= %
set LAST_WORD=
for %%i in (%PARENT_DIR%) do set LAST_WORD=%%i
echo %LAST_WORD%
This appears to get the current directory name, and stores it in the environment variable bar
:
for %i in (%CD%) do set bar=%~ni
This works because %CD%
contains the current directory, and %~n
strips the output of the for loop (looping for one value, %CD%
) to the 'file name' portion.
(Note, if you're using this in a batch file, use %%i
and %%~ni
instead.)
This doesn't, however, work for the root directory of a drive, it will instead unset bar
, as %~ni
will evaluate to nothing.
@pmod's answer (I lack the rep to comment) may work for root directories, but it doesn't work if there are spaces in the names.
Here's a slightly improved version (substituting / for space before splitting, then reverse substituting when finished).
call set PARENT_DIR=%CD%
set PARENT_DIR=%PARENT_DIR: =/%
set PARENT_DIR=%PARENT_DIR:\= %
set LAST_WORD=
for %%i in (%PARENT_DIR%) do set LAST_WORD=%%i
set LAST_WORD=%LAST_WORD:/= %
echo %LAST_WORD%
Pmod has a neater solution; I'm not sure mine works for root folders. But I thought I'd include it here for people to see.
set myPath=%cd%
pushd ..
set parentPath=%cd%
popd
echo myPath = "%myPath%"
echo parentPath = "%parentPath%"
call set myDir=%%myPath:%parentPath%\=%%
echo myDir = "%myDir%"
精彩评论