How to sort numeric variables ascending in DOS Batch?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
PiotrMP006
Posts: 31
Joined: 08 Sep 2017 06:10

How to sort numeric variables ascending in DOS Batch?

#1 Post by PiotrMP006 » 08 Sep 2017 06:13

How to sort numeric variables ascending in DOS Batch?

ex.

set number1=4
set number2=1
set number3=5
set number4=2
set number5=3

How to create a variable with sorted numbers

Result 1 2 3 4 5

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: How to sort numeric variables ascending in DOS Batch?

#2 Post by Squashman » 08 Sep 2017 06:57

The built in sort command within Windows does not have an option to sort numerically. So you will need to use a third party option.

Here are two options for you.
JSORT
SORTN

thefeduke
Posts: 211
Joined: 05 Apr 2015 13:06
Location: MA South Shore, USA

Re: How to sort numeric variables ascending in DOS Batch?

#3 Post by thefeduke » 12 Sep 2017 15:08

This solves your example in terms of input and desired output:

Code: Select all

@echo off &setlocal EnableDelayedExpansion

set number1=4
set number2=1
set number3=5
set number4=2
set number5=3

    >%Temp%\%~n0.txt Echo.
    For /L %%N in (1,1,5) Do >>%Temp%\%~n0.txt Echo.!number%%~N!
    Sort %Temp%\%~n0.txt /o %Temp%\%~n0.txt
    For /F %%N in ('Type %Temp%\%~n0.txt') Do Set "numbers=!numbers! %%~N"
    Echo.Result%numbers%

The example is limited. If your requirement is more than unsigned digits from 0-9, please define "number". If your number is on the left of the "=" then it is already sorted.

John A.

Post Reply