EDIT - New simple solution using JSORT.BAT
The native batch SORT command is extremely limited. I have written a convenient JSORT.BAT sorting utility that offers many convenient features, including the ability to sort strings with numbers based on the numeric value. JSORT.BAT is pure script (hybrid JScript/batch) that runs natively on any Windows machine without the need of any 3rd party exe files.
You can list the files numerically using
dir /b /a-d *.sql^|jsort /n /i
Simply put the command in a FOR /F loop if you want to iterate the results
for /f "delims=" %%F in ('dir /b /a-d *.sql^|jsort /n /i') do echo %%F
Full documentation is available from the command line using jsort /?
.
Original solution that predates JSORT.BAT
It is possible to do what you want with batch without modifying the file names, and it is farily efficient if you use a hybrid JScript/batch utility called REPL.BAT that performs a regex search and replace on stdin and writes the result to stdout. The utility is pure script that runs on any Windows machine from XP onward - no 3rd party executable required. Full documentation is embedded within the script.
Assuming REPL.BAT is in your current directory, or better yet, somewhere within your PATH, then the following will iterate .sql
files that start with a number in the desired sort order. As written, it supports numbers up to 5 digits long. It can easily be extended to support larger numbers.
@echo off
for /f "tokens=2 delims=:" %%F in (
'dir /b /a-d *.sql^|repl "^(\d+).*" "00000$1:$&" a^|repl ".*(\d{5}:)" "$1"^|sort'
) do echo %%F
This really shows the power of pipes :)
The complex IN() clause works as follows:
- List all .sql files
- Look for files that begin with a digit, and replace each matching name with the leading number prefixed with five leading zeros, followed by a colon, followed by the original name
- Replace the leading number, preserving only the last 5 digits
- Sort the result
The parent FOR /F then reads the result, parsing out the original file names as the second :
delimited token.