≡ Menu

Sort command

We can sort a text file using the windows inbuilt sort command. Below you can find the syntax of sort command.

Sort a text file:

A text file can be sorted using the below simple command.

sort filename

For example, to sort the file data.txt, the command would be
sort data.txt

The above command prints the sorted contents of the file in the console. To save the output into another file, you can use
/o switch as shown below.

sort filename /o outputfile


sort data.txt /o sorteddata.txt

Alternatively, you can user redirection operator.

sort data.txt > sorteddata.txt

Advanced options for sorting:

Sort the contents in reverse order

sort /R filename /o outputfile

If you are sorting big files, then /M switch will help you to finish the sorting quickly. Be default, sort command uses only 160 KB of space to store the file contents in main memory. Increasing this limit, will increase the performance of the sort operation. To let the sort command use 10MB of memory, we can run the below command.

sort /M 10240 data.txt /o sorteddata.txt
4 comments… add one
  • Stero

    I think the /M parameter is stated incorrectly here, please see the command line help info about /M:

    /M[EMORY] kilobytes Specifies amount of main memory to use for
    the sort, in kilobytes. The memory size is
    always constrained to be a minimum of 160
    kilobytes. If the memory size is specified
    the exact amount will be used for the sort,
    regardless of how much main memory is

    The best performance is usually achieved by
    not specifying a memory size. By default the
    sort will be done with one pass (no temporary
    file) if it fits in the default maximum
    memory size, otherwise the sort will be done
    in two passes (with the partially sorted data
    being stored in a temporary file) such that
    the amounts of memory used for both the sort
    and merge passes are equal. The default
    maximum memory size is 90% of available main
    memory if both the input and output are
    files, and 45% of main memory otherwise.

    If /M not specified, sort will try to utilize the as mush memory as possible, under this condition, the 160kb is the minimum memory not the maximum. If you specified /M, it will use that amount of memory exactly.

  • God

    This doesn’t work on Windows 7.
    Looks like the switches have disappeared.
    “help sort” just produces an error now too.

  • Leo

    To “God”, try this in Win7:

    sort /?

  • CmdrDick

    Works fine in Win7
    From All Programs, accessories, “command prompt”
    Command box will appear
    for directions type sort /?
    sort c:\infile.txt /O c:\outfile.txt
    May need to create an empty output file due to win restriction on writing files to c:\ without administrator permission

Leave a Comment