Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Dir command - order subdirectories by size

How could I display the subdirectories of a folder from largest to smallest using the dir command?

I've tried using dir /O:-S command, and although it sorts files just fine, it doesn't seem to order the subdirectories.

Ideally, the command should be able to go down several levels; some of these sub-folders have their own folders. For example:

D:/
|-- Folder 1
    |-- Subfolder 1
    +-- Subfolder 2
        |--Another folder
+-- Folder 2

Suppose the total size of Folder 1 (including all files in its subfolders) is 10GB, and that of Folder 2 is 15GB, how would I output their order sorted by total content size?

I.e.

94932485 Folder 2
6453445  Folder 1

Thanks in advance!

like image 873
Julian Laval Avatar asked Aug 18 '13 18:08

Julian Laval


2 Answers

If you are after a one-line solution, that supports upto 999 terabytes:

cmd /v /c "set zeropad=000,000,000,000,000,&for /f "delims=" %a in ('dir /ad /b') do @set bytes=!zeropad!000&(for /f "tokens=3" %b in ('dir /s "%a" 2^>NUL ^| find "File(s)"') do @set bytes=%b)& @for /f "tokens=1* delims=," %c in ('echo !bytes!') do @(set bytes=%c&@set bytes=000!bytes!&@set bytes=!bytes:~-3!& @set bytes=!zeropad!!bytes!&if "%d" NEQ "" set bytes=!bytes!,%d) & @echo !bytes:~-23! %a" | sort /R

And a bonus one-line solution if you want both files and directories

cmd /v /c "set zeropad=000,000,000,000,000,&for /f "tokens=4* delims= " %a in ('dir ^| find "/" ^| findstr /E /V /R "DIR^>[ ][ ]*\.\.$ DIR^>[ ][ ]*\.$"') do @set bytes=!zeropad!000&(if "%a" EQU "^<DIR^>" (for /f "tokens=3" %c in ('dir /s "%b" 2^>NUL ^| find "File(s)"') do @set bytes=%c)) & (if "%a" NEQ "^<DIR^>" (set bytes=%a)) & (for /f "tokens=1* delims=," %d in ('echo !bytes!') do @set bytes=%d&@set bytes=000!bytes!&@set bytes=!bytes:~-3!& @set bytes=!zeropad!!bytes!&if "%e" NEQ "" set bytes=!bytes!,%e)& echo !bytes:~-23! %b" | sort /R
like image 74
sparks Avatar answered Oct 16 '22 11:10

sparks


This seems to work for the changed requirements: alter c:\folder to the folder level you want to query.

@echo off
pushd "c:\folder"
for /f "delims=" %%a in (' dir /ad /b ') do call :size "%%~fa"
sort /r < "%temp%\dirsize.tmp"
del "%temp%\dirsize.tmp"
popd
pause
goto :eof

:size
for /f "tokens=3" %%b in ('dir /s "%~1" 2^>nul ^|find " File(s) "') do set "n=%%b"
set dirsize=%n%
REM set dirsize=%dirsize:,=%
set dirsize=                 %dirsize%
set dirsize=%dirsize:~-18%
>>"%temp%\dirsize.tmp" echo %dirsize% "%~1"
like image 28
foxidrive Avatar answered Oct 16 '22 13:10

foxidrive