【问题标题】:How to get the name of the directory for each file with a specific file extension in a directory tree?如何获取目录树中具有特定文件扩展名的每个文件的目录名称?
【发布时间】:2019-10-12 12:33:56
【问题描述】:

我需要获取指定文件夹/目录中每个扩展名为 *.txt 的文件的目录名称​​(包括其子文件夹/子目录)

我已经尝试过这里的解决方案:Parent folder from full path

但看起来set "myPath=%%~Pa" 在下面的代码中没有做任何事情:

@echo off

cd /d "F:\Game\"
for /r %%f in (*.txt) do (
    echo file: %%f
    set "myPath=%%~Pa"
    echo myPath: %myPath%
    for %%a in ("%myPath:~0,-1%") do (
        set "myParent=%%~Na"
        echo %myParent%
    )
)
pause.

对于这些文件:

F:\Game\file1.txt
F:\Game\first_subfolder\file2.txt
F:\Game\first_subfolder\hellothere\file3.txt
F:\Game\first_subfolder\hellothere\lala\file4.txt

我希望得到每个目录的名称:

Game
first_subfolder
hellothere
lala

如何获取目录树中每个文本文件的目录名?

【问题讨论】:

    标签: for-loop batch-file directory


    【解决方案1】:

    我建议首先打开一个command prompt 窗口,运行set /? 并阅读从第一页顶部到最后一页底部的输出帮助,尤其是关于延迟环境变量扩展的部分。另见:Variables are not behaving as expected

    但是可以不使用delayed expansion获取目录树中每个*.txt文件的目录名。

    @echo off
    for /R %%I in (*.txt) do for %%J in ("%%~dpI.") do (
        echo Text file: %%I
        echo Directory: %%~nxJ
    )
    

    注意:如果此批处理文件是从驱动器的根目录执行的并且该驱动器的根目录中有一个 *.txt 文件,%%~nxJ 是一个空字符串。

    这里的技巧是%%~dpI 扩展为以反斜杠结尾的当前文本文件的完整路径。 . 连接到此路径字符串以引用文件夹。然后%%~nxJ 扩展为没有路径的文件夹名称。另请参阅 Microsoft 文档页面 Naming Files, Paths, and Namespaces

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2022-07-21
      • 2014-07-30
      • 1970-01-01
      相关资源
      最近更新 更多