windowssortingbatch-filedirectorytimestamp

Sort files by Custom Timestamp with the Windows DIR command


I want to sort following files with DIR by their Timestamp, which is defined in the filename - oldest first: Timestamp = YYYYDDMM

NAME_20121410.dat
NAME_20121509.dat
NAME_20121609.dat

The result should look like this:

NAME_20121509.dat
NAME_20121609.dat
NAME_20121410.dat

How do i achieve that with an one-liner?


Solution

  • As the date format is stupid, you need to split first the filenames and sort the rearranged names.
    Not a one liner, but it works (inside a batch file).

    @echo off
    (
      for %%A in (*_*.dat) do @(
        call set "name=%%A"
        call set "nameDate=%%name:*_=%%"
        call set "Year=%%nameDate:~0,4%%"
        call set "Day=%%nameDate:~4,2%%"
        call set "Month=%%nameDate:~6,2%%"
        call echo %%Year%%%%Month%%%%Day%% %%name%%
      )
    ) | sort | (
      for /F "tokens=1,*  delims= " %%A in ('more') DO @echo %%B
    )