Link to home
Start Free TrialLog in
Avatar of Blowfelt82
Blowfelt82

asked on

Dir for loop get path details.

I have the following code...

FOR /f "delims=" %%f in ('dir /b /a-d-h c:\source\*.*') DO (
 Echo %%f >> Output
)

Open in new window


I know nothing about DOS but am looking to expand this in some way so that I can get both the file path and its name in separate variables? I also need a way of determining whether I am iterating on the first file in the loop - if so I want to use > to echo to a fresh file - otherwise I want to use >> to append to the file? Any ideas?
Avatar of oBdA
oBdA

You can access the path of a "for" variable X using "%~dpX" (see "help call" for details), the name and extension with %~nxX; and if you want to set and expand variables inside a "for" loop, you need delayed variable expansion (see "help set" for details):
@echo off
setlocal enabledelayedexpansion
set OutputFile=Output.txt
if exist "%OutputFile%" del "%OutputFile%"
FOR /f "delims=" %%f in ('dir /b /a-d-h c:\source\*.*') DO (
  set FilePath=%~dpf
  set FileName=%~nxf
  echo File path: !FilePath!
  echo File name: !FileName!
  echo %%f >>"%OutputFile%"
)

Open in new window

If you just want the overview, you can use this:
tree /f

Open in new window

Ok, try this.  Putting ( ) around commands will do it all in one go so one file operation creating file.  You can get different bits of file name and size etc. using operators on %%f, have shown some here to get path, name, size but see for /? for more.  I have changed %%f to %%F just to make it clearer in the other bits.  The ~ removes the "" characters around any files with spaces in so can re-add them to all for CSV type output.


@echo off
(FOR /f "delims=" %%F in ('dir /b /a-d-h c:\source\*.*') DO (
 Echo "%%~dpF","%%~nxF","%%~zF","%%~tF"
))> Output.csv
11 seconds slow there in posting :-)
Avatar of Blowfelt82

ASKER

Thanks for the posts so far, DragonIT your solution looks good but when I run it the %%~dpF command returns the path of the executing batch file and not of the file. This is I think an issue with my original DIR command which looking at it more closely does not include the path of the file in the output?
ASKER CERTIFIED SOLUTION
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect! Thanks for the help!
No problem, don't forget to "accept" the answer(s)
Sorry for the late 'Accept'!