1

To list the directories I use this:

set folder=C:\temp
for /d %%a in ("%folder%\*") do (
    echo %%~fa
)

To splith the file path I use this:

for %%f in (%MYDIR1%) do set myfolder=%%~nxf
echo %myfolder%

Now I want put both together:

@echo off

set folder=C:\Windows

for /d %%A in ("%folder%\*") do (
    for %%d in (%%~fA) do set lastfolder=%%~nxf
    echo %lastfolder%
)

All I get in thes result is %~nxf. I tried some things, but I didn't get a correct result. What I'm doing wrong?

What I don't understand in these examples is %~fA and %~nxf. Don't know where you can look up things like this.

Edit:

%~nxf to get file names with extensions

where F is the variable and ~n is the request for its name | Source

%~fI Expands %I to a fully qualified path name.

Now I modified my code with the new information:

@echo off

for /d %%A in ("%folder%\*") do (
    for %%D in (%%~fA) do (
        set lastfolder=%%~nxD
        echo %lastfolder%
    )
)

Now I get as result the last folder, but this is printed as many times as subfolders are existing. So I only get the last one. How can I iterate over each?

Solution:

Thanks to bgalea this is my solution:

@echo off
setlocal enabledelayedexpansion

set folder=C:\Windows

for /d %%A in ("%folder%\*") do (
    for %%D in (%%~fA) do (
        set lastfolder=%%~nxD
        echo !lastfolder!
    )
)

endlocal
Community
  • 1
  • 1
testing
  • 19,681
  • 50
  • 236
  • 417

1 Answers1

1

Things in bracket are one line. Therefore you have to use !var! which you turn on with setlocal enabledelayedexpansion. See set /? and setlocal /?.

. is current directory and .. is parent directory.

So c:\temp\.. is the same as c:\

%~nx1 etc are documented in the call command's help - call /?

My answer here Trouble with renaming folders and sub folders using Batch has a list of command prompt punctuation.

Community
  • 1
  • 1
  • Have you seen my edit? I tried it with `enabledelayedexpansion` and without but the results were the same. – testing Feb 20 '16 at 19:48
  • Have to use `!lastfolder!` not `%lastfolder%` –  Feb 20 '16 at 19:54
  • Reason why is that a variable name with exclamation marks is a valid MSDos variable. Hence having to turn on a special mode. –  Feb 20 '16 at 21:03