循环遍历文件夹字符串并解析出上一个文件夹名称 [英] Loop over folder string and parse out last folder name

查看:96
本文介绍了循环遍历文件夹字符串并解析出上一个文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取当前正在执行的批处理文件的文件夹名称.我一直在尝试使用以下语法循环当前目录(当前是错误的):

I need to grab the folder name of a currently executing batch file. I have been trying to loop over the current directory using the following syntax (which is wrong at present):

set mydir = %~p0
for /F "delims=\" %i IN (%mydir%) DO @echo %i

问题之所在,因为我似乎无法将'mydir'变量值作为搜索字符串传递.如果我传递命令,它似乎才起作用;我的语法错误,无法找出原因.

Couple of issues in that I cannot seem to pass the 'mydir' variable value in as the search string. It only seems to work if I pass in commands; I have the syntax wrong and cannot work out why.

我的想法是用'\'分隔符来循环文件夹字符串,但这也引起了问题.如果我在每个循环上设置一个变量,则最后一个值集将是当前文件夹名称.例如,给出以下路径:

My thinking was to loop over the folder string with a '\' delimiter but this is causing problems too. If I set a variable on each loop then the last value set will be the current folder name. For example, given the following path:

C:\ Folder1 \ Folder2 \ Folder3 \ Archive.bat

C:\Folder1\Folder2\Folder3\Archive.bat

我希望解析出值"Folder3".

I would expect to parse out the value 'Folder3'.

我需要解析该值,因为它的名称将是我要在批处理文件中进一步创建的另一个文件夹的一部分.

I need to parse that value out as its name will be part of another folder I am going to create further down in the batch file.

非常感谢任何人的帮助.我可能会完全把错误的树种成树,所以其他任何方法也将很受欢迎.

Many thanks if anyone can help. I may be barking up the wrong tree completely so any other approaches would be greatly received also.

推荐答案

您离它很近:)这应该可以工作:

You were pretty close to it :) This should work:

@echo OFF
set mydir="%~p0"
SET mydir=%mydir:\=;%

for /F "tokens=* delims=;" %%i IN (%mydir%) DO call :LAST_FOLDER %%i
goto :EOF

:LAST_FOLDER
if "%1"=="" (
    @echo %LAST%
    goto :EOF
)

set LAST=%1
SHIFT

goto :LAST_FOLDER

由于某种原因,for命令不喜欢将'\'作为分隔符,因此我将所有的'\'转换为';'首先(SET mydir=%mydir:\=;%)

For some reason the for command doesn't like '\' as a delimiter, so I converted all '\' to ';' first (SET mydir=%mydir:\=;%)

这篇关于循环遍历文件夹字符串并解析出上一个文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆