我完全与路径混淆。 我有根文件夹的变量
set root=D:\Data\Finished
我用一个包含文件路径的参数调用批处理文件
c:\test\1.bat D:\Data\Finished\folder1\1.txt
c:\test\1.bat D:\Data\Finished\folder2\folder3\1.txt
c:\test\1.bat D:\Data\Finished\1.txt
如何在root之后获取路径中的第一个文件夹?如果没有文件夹 - 返回root?即:
D:\Data\Finished\folder1
D:\Data\Finished\folder2
D:\Data\Finished\
我的代码
call :setfile %FILENAME%
call :parentfolder %file_path:~0,-1%
if "%file_parent%"=="D:\Data\" (
set ut_dir=%file_path%
) else (
if "%file_parent%"=="D:\Data\Finished\" (
set ut_dir=%file_path%
) else (
set ut_dir=%file_parent%
)
)
:setfile
set file=%~f1
set file_path=%~dp1
set file_name=%~nx1
goto :eof
:parentfolder
set file_parent=%~dp1
goto :eof
答案 0 :(得分:1)
@echo off
setlocal EnableDelayedExpansion
set root=D:\Data\Finished
set "thePath=%~DP1"
set "result=%root%\"
for /F "delims=\" %%a in ("!thePath:%root%\=!") do set "result=%root%\%%a"
echo %result%
输出示例:
C:\> test.bat D:\Data\Finished\folder1\1.txt
D:\Data\Finished\folder1
C:\> test.bat D:\Data\Finished\folder2\folder3\1.txt
D:\Data\Finished\folder2
C:\> test.bat D:\Data\Finished\1.txt
D:\Data\Finished\