1

I need to get the name of the directory for each file with extension *.txt within specified folder/directory (including its subfolders/subdirectories).

I've tried the solution from here: Parent folder from full path

But it looks like that set "myPath=%%~Pa" doesn't do anything in the code below:

@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.

For these files:

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

I expect to get the name of the directory for each of them:

Game
first_subfolder
hellothere
lala

How to get the name of the directory for each text file in directory tree?

Mofi
  • 46,139
  • 17
  • 80
  • 143
Thordiato
  • 13
  • 2

1 Answers1

1

I suggest first opening a command prompt window, running set /? and reading the output help from topĀ of first page to bottom of last page, especially the section about delayed environment variable expansion. See also: Variables are not behaving as expected.

But it is possible to get the directory name for each *.txt file in directory tree without using delayed expansion.

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

Note: %%~nxJ is an empty string if this batch file is executed from root of a drive and there is a *.txt file in root of this drive.

The trick here is %%~dpI expands to full path of current text file ending with a backslash. . is concatenated to this path string to reference the folder. Then %%~nxJ expands to name of the folder without path. See also the Microsoft documentation page Naming Files, Paths, and Namespaces.

Mofi
  • 46,139
  • 17
  • 80
  • 143