ArticleslgStudy

computer science

Sort (Unix)

Sort (Unix) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Sort (Unix) rather than just read about it. In short: In computing, sort is a standard command line program of Unix and Unix-like operating systems, that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. Sorting is done based on one or more sort keys extracted from each line of input.

Sort (Unix) — main illustration
Sort (Unix) — illustration

Key takeaways

  • Sort (Unix) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Sort (Unix) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Sort (Unix) from memory before moving on to harder problems.

Reference excerpt

In computing, sort is a standard command line program of Unix and Unix-like operating systems, that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. Sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as sort key. Blank space is the default field separator. The command supports a number of command-line options that can vary by implementation. For instance the "-r" flag will reverse the sort order. Sort ordering is affected by the environment's locale settings.

History A sort command that invokes a general sort facility was first implemented within Multics. Later, it appeared in Version 1 Unix. This version was originally written by Ken Thompson at AT&T Bell Laboratories. By Version 4 Thompson had modified it to use pipes, but sort retained an option to name the output file because it was used to sort a file in place. In Version 5, Thompson invented "-" to represent standard input. sort is part of X/Open Portability Guide Issue 2 (1987). From there it was inherited into POSIX. The version of sort bundled in GNU coreutils was written by Mike Haertel and Paul Eggert. This implementation employs the mergesort algorithm. It offers an option to sort in parallel, though performance gain diminishes after 8 threads. GNU parallel also provides a wrapper to perform parallel invocations of sort with similar performance-gain characteristics: on a 48-core system, the speedup is about 3×. The sort command has also been ported to the IBM i operating system, being accessible from the POSIX-compatible Qshell.

Non-POSIX ports Similar commands are available on many other operating systems, for example a sort command is part of ASCII's MSX-DOS2 Tools for MSX-DOS version 2. The "uutils" project provides a cross-platform implementation of sort written in Rust, with support for all of GNU coreutil's options. It uses the par_sort_by or par_sort_unstable_by function of Rayon, the Rust multi-threading library, implementing either an adaptive mergesort inspired by timsort or a variation of pattern-defeating quicksort.

Syntax sort [OPTION]... [FILE]...

With no FILE, or when FILE is -, the command reads from standard input.

Parameters In the table below, "Short" indicates only support for the one-letter (short) form of the option. Long options are originally a GNU extension and is not part of any version of SUS or POSIX. It has since also been adopted by FreeBSD.

Examples

Sort a file in alphabetical order

Sort by number The -n option makes the program sort according to numerical value. The du command produces output that starts with a number, the file size, so its output can be piped to sort to produce a list of files sorted by (ascending) file size:

The find command with the ls option prints file sizes in the 7th field, so a list of the LaTeX files sorted by file size is produced by:

Columns or fields Use the -k option to sort on a certain column. For example, use "-k 2" to sort on the second column. In old versions of sort, the +1 option made the program sort on the second column of data (+2 for the third, etc.). This usage is deprecated.

Sort on multiple fields The -k m,n option lets you sort on a key that is potentially composed of multiple fields (start at column m, end at column n):

Here the first sort is done using column 2. -k2,2n specifies sorting on the key starting and ending with column 2, and sorting numerically. If -k2 is used instead, the sort key would begin at column 2 and extend to the end of the line, spanning all the fields in between. -k1,1 dictates breaking ties using the value in column 1, sorting alphabetically by default. Note that bob, and chad have the same quota and are sorted alphabetically in the final output.

Sorting a pipe delimited file

Sorting a tab delimited file Sorting a file with tab separated values requires a tab character to be specified as the column delimiter. This illustration uses the shell's dollar-quote notation to specify the tab as a C escape sequence.

Sort in reverse The -r option just reverses the order of the sort:

Sort in random The GNU implementation has a -R --random-sort option based on hashing; this is not a full random shuffle because it will sort identical lines together. A true random sort is provided by the Unix utility shuf.

Sort by version The GNU implementation has a -V --version-sort option which is a natural sort of (version) numbers within text. Two text strings that are to be compared are split into blocks of letters and blocks of digits. Blocks of letters are compared alpha-numerically, and blocks of digits are compared numerically (i.e., skipping leading zeros, more digits means larger, otherwise the leftmost digits that differ determine the result). Blocks are compared left-to-right and the first non-equal block in that loop decides which text is larger. This happens to work for IP addresses, Debian package version strings and similar tasks where numbers of variable length are embedded in strings.

See also Collation List of Unix commands uniq shuf join (Unix)

References

Further reading Shotts (Jr), William E. (2012). The Linux Command Line: A Complete Introduction. No Starch Press. ISBN 978-1593273897. McElhearn, Kirk (2006). The Mac OS X Command Line: Unix Under the Hood. John Wiley & Sons. ISBN 978-0470113851.

External links

Original Sort manpage The original BSD Unix program's manpage sort(1) – Linux User Manual – User Commands from Manned.org sort(1) – Plan 9 Programmer's Manual, Volume 1 sort(1) – Inferno General commands Manual Further details about sort at Softpanorama

Illustrations

Sort (Unix) illustration

Worked examples

Example 1 — a first encounter with Sort (Unix)

Start with the simplest possible case. Write down what Sort (Unix) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Sort (Unix) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Sort (Unix) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Sort (Unix)

In research
Sort (Unix) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Sort (Unix) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Sort (Unix) is common in secondary-school and first-year university syllabi. It links to neighbouring topics IBM i Qshell commands, Inferno (operating system) commands, Plan 9 commands, so understanding it makes those chapters shorter.
In everyday life
Look for Sort (Unix) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Sort (Unix) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Sort (Unix) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Sort (Unix) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Sort (Unix) in simple terms?

In computing, sort is a standard command line program of Unix and Unix-like operating systems, that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. Sorting is done based on one or more sort keys extracted from each line of input.

Why does Sort (Unix) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Sort (Unix)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Sort (Unix).

Tags

  • IBM i Qshell commands
  • Inferno (operating system) commands
  • Plan 9 commands
  • Sorting algorithms
  • Standard Unix programs
  • Unix SUS2008 utilities
  • Unix text processing utilities

Keep exploring