0

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

2
  • 2
    Dir /B/A-D/OE …enter Dir /? at the command prompt for usage information. Commented Apr 28, 2018 at 22:16
  • The order you get with a for loop depends on the underlying file system. Only ntfs sorts with alpha sort by default. For also doesn't obey the environment var `Dircmd" Commented Apr 28, 2018 at 23:26

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

For the second method, it's supposed to output [DIR], not <DIR> right? I'm still getting <DIR> outputted.
I'm going to assume that the output from your Dir command contains an extra token. The method is not robust enough then due to locale settings differences. To get the output though you'd probably need to use Tokens=4*
That works great. Is there any way to order the directories in alphabetical order?
@DerekZhang dir /OEGN should group directories first, in alphapetical order, then files by extension.

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.