How to extract a complete list of extension types within a directory

This batch script will do it.

@echo off

set target=%1
if "%target%"=="" set target=%cd%

setlocal EnableDelayedExpansion

set LF=^

rem Previous two lines deliberately left blank for LF to work.

for /f "tokens=*" %%i in ('dir /b /s /a:-d "%target%"') do (
    set ext=%%~xi
    if "!ext!"=="" set ext=FileWithNoExtension
    echo !extlist! | find "!ext!" > nul
    if not !ERRORLEVEL! == 0 set extlist=!extlist!!ext!:

echo %extlist::=!LF!%

Save it as any .bat file, and run it with the command batchfile (substitute whatever you named it) to list the current directory, or specify a path with batchfile "path". It will search all subdirectories.
If you want to export to a file, use batchfile >filename.txt (or batchfile "path" >filename.txt).


Everything before the for /f... line just sets things up: it gets the target directory to search, sets delayed expansion which lets me do some magic with the variables in the loop and defines a newline (LF) that I can use for neater output.

The loop uses that dir /b /s /a:-d "%target%" command, grabbing a list of all files in all subdirectories under the target.

%%~xi extracts the extension out of the full paths the dir command returns.

An empty extension is replaced with "FileWithNoExtension", so you know there is such a file - if I added an empty line instead, it's not quite as obvious.

The whole current list if sent through a find command, to ensure uniqueness. The output of the find command is sent to nul, essentially a black hole - we don't want it.

%ERRORLEVEL% is set by the find command, a value of 0 indicates there was a match. So if it's not 0, the current extension is not on the list so far and should be added.

The echo line basically outputs, and I also replace my placeholders (:) with newlines to make it look nice.

No comments:

Post a Comment