0

I want to traverse all files within a specific directory and all its subdirectories and then print out the folder name of each file.

I don't know how to get the folder name of each file.

FOR /F "delims=" %%x IN ('dir /B /A /S *') DO (
    :: Suppose %%x is 'C:\myfolder\a.txt', the desired output is 'myfolder'
    :: %%~nx is not correct
    echo ???
)
4
  • 2
    n is for filename. Check for /? for other options. You can combine the different options. You probably look for %%~dpx Commented Jan 22, 2016 at 15:39
  • Did you read the help for the FOR command? Commented Jan 22, 2016 at 15:39
  • @Squashman "uhh - that is sooo much text..." Commented Jan 22, 2016 at 15:41
  • Please note that DOS is an Operating System from the 80s/90s! Please use the tag Windows instead. Commented Aug 23, 2017 at 6:01

2 Answers 2

4

If you want just the path (without drive, without filename), %%~px is what you need

If you want just the last folder, not the complete path. This is indeed not that trivial:

@echo off 
setlocal enabledelayedexpansion
for /f "delims=" %%x in ('dir /b /a /s *') do (
  set "line=%%~dpx"
  for /f "delims=" %%y in ("!line:\=.!") do set folder=%%~xy
  echo %%~nxx is in:  !folder:~1!
)
Sign up to request clarification or add additional context in comments.

3 Comments

Did I just beat the almighty Stephan by 31 seconds? Oh my.
"almighty"? There are other names here that come to my mind :D Nevertheless - your's is better (assuming we understood the question right)
@Stephan, your inner FOR can just be this: for %%y in ("%%~dpx\.") do echo %%~nxy. Your inner FOR will have problems with Folders that are named with periods. I just noticed that is what Dennis did but his also suffers from the periods.
3

I think this is what you're looking for:

@echo off
FOR /F "delims=" %%F IN ('dir /B /A /S *') DO (
for %%D in ("%%~dpF\.") do echo %%~nxD
)
pause

3 Comments

Your ECHO needs the x modifier as well otherwise it will not be able to handle folder names with periods.
@Squashman you're right, to be honest the first version had that but I forgot what it was for and removed it
Thanks, this is what I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.