windows 拆分路径并在批处理脚本中取最后一个文件夹名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17279114/
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-09 10:37:54  来源:igfitidea点击:

split path and take last folder name in batch script

windowsfor-loopbatch-filecmddirectory

提问by user2013

I want to split the string (having a path) with \and take last folder name in a variable. Please help.

我想拆分字符串(具有路径)\并在变量中取最后一个文件夹名称。请帮忙。

e.g
mypath=D:\FOLDER1\FOLDER2\FOLDER3\

例如
mypath=D:\FOLDER1\FOLDER2\FOLDER3\

I want FOLDER3 in a variable.

我想要一个变量中的 FOLDER3。

I tried with the command below which is working if the the last character is not \:

如果最后一个字符不是,我尝试使用下面的命令\

for %f in (C:\FOLDER1\FOLDER2\FOLDER3) do set myfolder=%~nxf

It is not working if the last character is \

如果最后一个字符是 \

Also it is not working if variable is used like : for %f in (%mypath%) do set myfolder=%~nxf

如果像这样使用变量,它也不起作用: for %f in (%mypath%) do set myfolder=%~nxf

回答by user93353

@echo off

set MYDIR=C:\FOLDER1\FOLDER2\FOLDER3\
set MYDIR1=%MYDIR:~0,-1%

for %%f in (%MYDIR1%) do set myfolder=%%~nxf
echo %myfolder%

outputs

产出

FOLDER3

回答by Endoro

try:

尝试:

for %f in (C:\FOLDER1\FOLDER2\FOLDER3\.) do set myfolder=%~nxf

works also:

也有效:

for %f in (C:\FOLDER1\FOLDER2\FOLDER3.) do set myfolder=%~nxf

回答by Dirk

When your current folder contains spaces then try this:

当您的当前文件夹包含空格时,请尝试以下操作:

@echo off
for %%f in ("%CD%") do set LastPartOfFolder=%%~nxf

echo %LastPartOfFolder%