windows 如何在命令提示符中获取父文件夹的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3003885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:37:20  来源:igfitidea点击:

How do I get the name of the parent folder in a command prompt?

windowscommand-linecommand-prompt

提问by Bernhard Hofmann

I'm in a Windows Command Line and want the parent folder in a variable.

我在 Windows 命令行中并希望父文件夹位于变量中。

Assuming current directory is "C:\foo\bar", how can I get the value "bar"?

假设当前目录是“C:\foo\bar”,我怎样才能得到值“bar”?

I'm expecting something like a "find last backslash in CD and that's it".

我期待诸如“在 CD 中找到最后一个反斜杠,仅此而已”之类的东西。

And please, no powershell references; I want plain old Windows Command Line operations.

请不要引用 powershell;我想要普通的旧 Windows 命令行操作。

回答by pmod

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%

回答by Blair Holloway

This appears to get the current directory name, and stores it in the environment variable bar:

这似乎获取当前目录名称,并将其存储在环境变量中bar

for %i in (%CD%) do set bar=%~ni

This works because %CD%contains the current directory, and %~nstrips the output of the for loop (looping for one value, %CD%) to the 'file name' portion.

这是有效的,因为%CD%包含当前目录,并将%~nfor 循环的输出(循环一个值,%CD%)剥离到“文件名”部分。

(Note, if you're using this in a batch file, use %%iand %%~niinstead.)

(注意,如果您在批处理文件中使用它,请使用%%iand%%~ni代替。)

This doesn't, however, work for the root directory of a drive, it will instead unset bar, as %~niwill evaluate to nothing.

然而,这不适用于驱动器的根目录,它会改为 unset bar,因为%~ni将评估为空。

回答by Bernhard Hofmann

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.

Pmod 有一个更简洁的解决方案;我不确定我的是否适用于根文件夹。但我想我会把它包括在这里让人们看到。

set myPath=%cd%
pushd ..
set parentPath=%cd%
popd
echo myPath = "%myPath%"
echo parentPath = "%parentPath%"
call set myDir=%%myPath:%parentPath%\=%%
echo myDir = "%myDir%"

回答by mojo

@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.

@pmod 的回答(我缺少评论的代表)可能适用于根目录,但如果名称中有空格则不起作用。

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%