【问题标题】:windows batch Iterate tokens in a for loopwindows批处理在for循环中迭代令牌
【发布时间】:2013-01-24 17:14:41
【问题描述】:

如何在 Windows 批处理脚本的 for 循环中遍历标记?

我正在编写一个脚本,允许用户搜索文件并打印出该文件的父目录。到目前为止,我可以从文件名中获取完整路径,但我只需要父目录。工作正常,但希望有一种更有效的方式来遍历令牌。

这是我所拥有的一个片段。 file 变量是要搜索的文件,Path 变量是文件的完整路径。

fOR /F "tokens=1-25 delims=\" %%i IN ("!thePath!") DO (

    if %%j equ %file% set theParent= %%i
    if %%k equ %file% set theParent= %%j
    if %%l equ %file% set theParent= %%k
    if %%m equ %file% set theParent= %%l
    if %%n equ %file% set theParent= %%m
    if %%o equ %file% set theParent= %%n
    if %%p equ %file% set theParent= %%o
    if %%q equ %file% set theParent= %%p
    if %%r equ %file% set theParent= %%q
    if %%s equ %file% set theParent= %%r
    if %%t equ %file% set theParent= %%s
    if %%u equ %file% set theParent= %%t
    if %%v equ %file% set theParent= %%u
    if %%w equ %file% set theParent= %%v
    if %%x equ %file% set theParent= %%w
    if %%y equ %file% set theParent= %%x
    if %%z equ %file% set theParent= %%y


)
echo The parent directory is: %theParent%

【问题讨论】:

    标签: windows for-loop batch-file token loops


    【解决方案1】:

    您的方法无法可靠地工作,因为文件可能与其父文件夹之一同名。

    无需迭代 FOR /F 标记。您可以使用简单的 FOR 直接获取父文件夹 :-)

    for %%F in ("!thePath!\..") do set "theParent=%%~nxF"
    echo The parent directory is: !theParent!
    

    注意 - 如果文件在根目录中,theParent 将是未定义的(空的)。

    【讨论】:

    • +1 简单高效的答案! 简短说明: \.. 告诉命令行解释器检索指定路径的父目录。 for 循环只运行一次,用于将路径转换为带有修饰符 %%~nxF 的变量。
    • 太棒了!这正是我一直在寻找的。我实际上尝试了你在这里的 for 循环,但它只返回文件名。 \.. 是这里的关键。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2013-01-25
    • 2014-08-24
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多