sort - macOS
Overview
sort is a versatile command-line utility for sorting text files or input data. It’s widely used in macOS and Linux systems to organize and rearrange data based on specific criteria.
Syntax
sort [options] [files]
Options/Flags
- -b: Ignore leading blanks and tabs when sorting.
- -c: Check for already-sorted files; report errors if unsorted.
- -d: Sort in dictionary order (case-insensitive).
- -f: Fold case (upper and lower case are considered equal).
- -i: Ignore non-printing characters (e.g., tabs).
- -k: Specify a key field with the following syntax:
-k [field],[type](field: number or POSIX character class; type: letter, number, or month). - -n: Sort numerically instead of lexicographically.
- -o: Output the sorted data to a file.
- -r: Reverse the sorting order.
- -t: Use the specified character as the field separator.
- -u: Remove duplicate lines from the output.
- -V: Print the version of
sortand exit. - -z: Terminate lines with a null character instead of a newline.
Examples
- Simple sorting:
sort file1.txt - Reverse numerical sorting:
sort -n -r file2.txt - Sort by the second field:
sort -k 2 file3.txt - Ignore leading whitespace:
sort -b file4.txt - Output to a file:
sort file5.txt -o sorted.txt
Common Issues
- Incorrect field separator: Check the
-toption to ensure it matches the data. - Unsorted input: Use the
-coption to check if the input is already sorted. - Ambiguous sort criteria: Specify multiple sort keys using
-kto resolve ambiguities.
Integration
sort integrates well with other commands, such as:
cutandpastefor extracting and sorting specific fields.uniqfor removing duplicate lines after sorting.awkfor advanced data manipulation and sorting.
Related Commands
grepwcnl