【问题标题】:Batch : getting the last folder name from a absolute path批处理:从绝对路径获取最后一个文件夹名称
【发布时间】:2011-08-30 22:27:33
【问题描述】:

我正在使用批处理脚本自动将文件备份到我的 NAS,我需要从绝对路径获取最后一个文件夹名称,例如从“C:\Things\Folder”到“Folder”

【问题讨论】:

    标签: path batch-file directory absolute


    【解决方案1】:

    这有点小技巧,但你可以使用:

    Set NasPath=C:\Things\Folder
    Set NasFolder=%NasPath%
    :GetFolder
    Set GetFolderTemp=%NasFolder:*\=%
    If Not %GetFolderTemp%==%NasFolder% (
        Set NasFolder=%GetFolderTemp%
        Goto :GetFolder
    )
    Echo NasPath  =%NasPath%
    Echo NasFolder=%NasFolder%
    Exit /B
    

    无论您做什么,都不要在Set NasPath=... 语句的任何部分加上引号。以这种方式使用引号:

    Set FromPath=C:\Program Files\Blah
    Set NasPath=C:\Things\Folder
    RoboCopy "%FromPath%" "%NasPath%"
    

    不要这样使用引号:

    Set FromPath="C:\Program Files\Blah"
    Set NasPath="C:\Things\Folder"
    RoboCopy %FromPath% %NasPath%
    

    【讨论】:

    • +1,但是您应该始终以这种方式使用引号 Set "FromPath=C:\Program Files\Blah" 否则您将失败 Set FromPath=C:\Documents & Settings
    • @jeb SET FromPath=C:\Docs and Settings 有效。就像@Hand-E 所说,要使用变量,请将其括在引号中,"%FromPath%"
    • 很明显Docs and Settings 可以工作,但是使用&符号会失败,并且文件/路径名中允许&符号
    【解决方案2】:

    为了对空间没有任何问题,我建议使用以下代码:

    Set NasPath=C:\Things\My Space\Folder
    Set GetFolderTemp=%NasPath%
    :GetFolder
    FOR /F "tokens=1,* delims=\" %%1 IN ("%GetFolderTemp%") do (
    set NasFolder=%%1
    set GetFolderTemp=%%2
    )
    if not "a%GetFolderTemp%"=="a" goto :GetFolder
    
    echo %NasFolder%
    

    【讨论】:

      【解决方案3】:

      假设C:\Program Files\Mickey\Mouse-like 路径(不带引号),您还可以使用以下代码:

      setlocal EnableDelayedExpansion
      
      set path=C:\Program Files\Microsoft\Mickey\Mouse
      :shift
      for /f "tokens=1* delims=\/" %%i in ( "!path!" ) do (
          set folder=%%i
          set path=%%j
      )
      if not [!path!] == [] goto :shift
      
      echo folder: !folder!
      
      endlocal
      

      【讨论】:

      • 请注意,这将覆盖PATH 环境变量。
      猜你喜欢
      • 1970-01-01
      • 2011-05-17
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多