Sort, merge, or sequence-check text files (POSIX)
sort [-9m] [-o name] [-bdfinru] [-t char] [-k keydef] [+oldkey] [file...] sort [-9c] [-bdfinru] [-t char] [-k keydef] [+oldkey] [file]
QNX Neutrino, Microsoft Windows
The following options override the default ordering rules. When ordering options appear independent of key field specifications, the requested field ordering rules are applied globally to all sort keys. When attached to a specific key (see option -k), the specified ordering options override all global ordering options for that key.
The sort utility orders lines from a set of files (or standard input if no files are provided) and merges the output into the specified output (or standard output if no output file is specified). The sort utility provides a number of options for controlling the sorting mechanism. The default behavior of sort is to treat all lines as a sequence of characters to be sorted in ascending order.
The sort utility regards files and file contents the following way:
The -t option has subtle effects. If you don't use the option, only the first blank in a string of blank characters is interpreted as a field separator; the remaining are considered part of the next field. If you use the -t option, every occurrence of the field separator character is considered a terminator for a field. Thus, four adjacent field separators represent three empty fields.
A sort key field may be defined using the following syntax:
-k field_start [type_string] [,field_end] [type_string]
where field_start and field_end specify the beginning and end of the key field, and type_string is used to specify attributes specific to the key.
The field_start and field_end are each specified by a pair of digits of the form m.n, where the m refers to the field starting after the mth field separator in a line. For field_start, the .n refers to the nth character of the specified field, and is taken as zero if not specified. For field_end, the .n refers to the nth character after the last character of the specified field, and is taken as zero if not specified.
The type_string may be formed from the characters bdfinr, which apply their defined attributes to the determination of the key.
There is another mechanism (+oldkey) for defining sort keys, which remains for historical reasons. The syntax of this mechanism is:
+field_start [type_string] -field_end [type_string]
The semantics are the same as for the -k option.
The following command sorts the password database by gid, then uid, then username:
sort -t: -k 3.0n -k 2.0n -k 0.0d /etc/passwd
Notice that the type_string attached to field_string is used to determine the type of comparison with this key.
The second type_string is solely to adjust the extent of the sort_key, thus only i and b make any sense. Any other characters are ignored.
The standard password file has the form:
username:password:uid:gid:misc:home:shell
Sort the password database by username:
sort -t: /etc/passwd