Derek Zhang
Derek Zhang

Reputation: 47

Batch Script - Displaying files and directory in sorted order

So I'm trying to make my own dir command for cmd. So far it is working great, except I want to output the directories and files sorted by file extension, in the way

dir /o:ge

would display (folders first, then files sorted by file extension). So far, my code looks like this

@echo off

rem Title
echo.
echo CURRENT DIRECTORY [%cd%]
echo. 
rem Directories
for /d %%D in (*) do (
    echo [DIR] %%~nD
)

rem Files
for %%F in (*) do (
    echo %%~nxF
)
@echo on

This produces:

Example

I'm not sure how to approach outputting the files sorted by file extension. I have searched the web and can't find a solution to this problem. I do realize batch script is very limited, but I still want to try and implement this. I have thought of using a for loop and storing all the file extensions into an "array" (if that exists in batch), and then outputting them by

*.fileExtension

Any suggestions?

Cheers, Derek

Upvotes: 0

Views: 2867

Answers (1)

Compo
Compo

Reputation: 38589

As in my comment…

@Echo Off
Echo  CURRENT DIRECTORY [%__CD__:~,-1%]&Echo(
For /F "EOL= Tokens=* Delims= " %%A In ('Dir /B/AD/ON') Do Echo  [DIR] %%A
For /F "EOL= Tokens=* Delims= " %%A In ('Dir /B/A-D/OE') Do Echo  %%A
Echo(&Pause>Nul

Alternatively…

@Echo Off
Echo  CURRENT DIRECTORY [%__CD__:~,-1%]&Echo(
For /F "EOL= Delims=" %%A In ('Dir /OGE/-C'
) Do For /F "Tokens=3*" %%B In ("%%A"
) Do If "%%B"=="<DIR>" (If Not "%%C"=="." If Not "%%C"==".." Echo  [DIR] %%C
) Else Echo  %%C
Echo(&Pause>Nul

Upvotes: 1

Related Questions