首页 > 解决方案 > 在 Windows CMD 中提取给定的祖先路径形成更深的路径

问题描述

我不知道如何使用 Win CMD 批处理脚本来获取此处描述的内容:

伪代码

set aPath=C:\just\a\long\path\to\a\file\in\the\file\system
set aDir=file
... some logic here 
echo %result%

应该打印

C:\just\a\long\path\to\a\file

它应该在找到的第一次出现时停止,但最好也指定出现(可选)。

只欢迎 Windows CMD 解决方案,请不要使用 Powershell 代码或外部工具。我正在寻找一个纯 Windows CMD 解决方案。

标签: windowsbatch-file

解决方案


我不太确定你指的是什么

使用随机播放方法和自我修改代码来获取目录级别

:: Q:\Test\2019\08\29\SO_57717256.cmd
@Echo off & Setlocal EnableDelayedExpansion

set "aPath=C:\just\a\long\path\to\a\file\in\the\file\system"
set "aDir=file"
echo aPath = %aPath%
echo aDir  = %aDir%

::... some logic here 
set "intermediate=!apath:*%aDir%=!"
set "result=!aPath:%intermediate%=!"

:: and some vodoo there ;-)
Set i=0
Set "aPath=%aPath:\="&Set /a i+=1&Set "aPath[!i!]=%"

echo result= %result%

for /l %%L in (1,1,%i%) Do if "%aDir%"=="!aPath[%%L]!" (
    echo aPath[%%L] = !aPath[%%L]! ^<^<^< matches aDir %aDir%
) else (
    echo aPath[%%L] = !aPath[%%L]!
)

样本输出:

> Q:\Test\2019\08\29\SO_57717256.cmd
aPath = C:\just\a\long\path\to\a\file\in\the\file\system
aDir  = file
result= C:\just\a\long\path\to\a\file
aPath[1] = just
aPath[2] = a
aPath[3] = long
aPath[4] = path
aPath[5] = to
aPath[6] = a
aPath[7] = file <<< matches aDir file
aPath[8] = in
aPath[9] = the
aPath[10] = file <<< matches aDir file
aPath[11] = system

推荐阅读