如何从完整路径的文件名中删除最后2个文件夹名称?

时间:2017-10-17 04:37:12

标签: batch-file

如何使用批处理脚本删除文件路径中的最后2个文件夹?

结果应该是最后4个文件夹路径。

C:\Test\Test01\Test02\Test03\Test04\Test05\Test06\Test.txt

应该是这样的:

C:\Test\Test01\Test02\Test03\Test04

1 个答案:

答案 0 :(得分:0)

以下是此任务的注释批处理代码:

@echo off
rem Is the batch file not called with an argument which
rem is expected to be the name of a file with full path?
if "%~1" == "" goto DemoCode

rem This code demonstrates how to get path to last but one folder
rem with accessing the file system and therefore working only if
rem the specified file respectively its folders really exist.

for %%I in ("%~dp1..\..\") do set "FilePath=%%~dpI"

rem Remove the backslash at end.
set "FilePath=%FilePath:~0,-1%"
goto DisplayResult


rem The demo code below demonstrates how to remove file name
rem and last two folders in path from a file name string with
rem complete path without accessing the file system at all.

:DemoCode
rem Get path of file ending with a backslash.
for /F "delims=" %%I in ("C:\Test\Test01\Test02\Test03\Test04\Test05\Test06\Test.txt") do set "FilePath=%%~dpI"

rem Remove the backslash at end.
set "FilePath=%FilePath:~0,-1%"

rem Get path to last folder of original file name with full path.
for /F "delims=" %%I in ("%FilePath%") do set "FilePath=%%~dpI"

rem Remove the backslash at end.
set "FilePath=%FilePath:~0,-1%"

rem Get path to last but one folder of original file name with full path.
for /F "delims=" %%I in ("%FilePath%") do set "FilePath=%%~dpI"

rem Remove the backslash at end a last time.
set "FilePath=%FilePath:~0,-1%"

:DisplayResult
echo/
echo File path is: %FilePath%
echo/
set "FilePath="
pause

评论解释有两个例子。

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • call /? ...解释%~1(删除了周围双引号的第一个参数字符串)和%~dp1(第一个参数的驱动器和路径)。
  • echo /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • rem /?
  • set /?