Cheat Sheet #day61 - sort

Cloud TunedCloud Tuned
2 min read

sort Command Cheatsheet

The sort command in Unix-like systems is used to sort lines of text files. It is highly configurable and supports various sorting criteria. Here’s a quick reference guide:

Basic Syntax

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

Common Options

  • -o FILE: Write the output to FILE instead of standard output.

      sort -o sorted.txt unsorted.txt
    
  • -n, --numeric-sort: Compare according to string numerical value.

      sort -n numbers.txt
    
  • -r, --reverse: Reverse the result of comparisons.

      sort -r file.txt
    
  • -k FIELD, --key=FIELD: Sort by a specific field. Fields are separated by tabs or spaces.

      sort -k 2 file.txt  # Sort by the second field
    
  • -t CHAR, --field-separator=CHAR: Use CHAR as the field separator (default is whitespace).

      sort -t, -k 1,1 file.txt  # Sort by the first field, assuming fields are separated by commas
    
  • -u, --unique: Output only the first of an equal run.

      sort -u file.txt
    
  • -f, --ignore-case: Fold lower case to upper case characters.

      sort -f file.txt
    
  • -u, --unique: Output only the first of an equal run.

      sort -u file.txt
    
  • -b, --ignore-leading-blanks: Ignore leading blanks.

      sort -b file.txt
    

Examples

  1. Sort lines in a file alphabetically:

     sort file.txt
    
  2. Sort numerically:

     sort -n numbers.txt
    
  3. Reverse the order:

     sort -r file.txt
    
  4. Sort by the second field:

     sort -k 2 file.txt
    
  5. Sort by a custom delimiter (e.g., comma):

     sort -t, -k 1,1 file.txt
    
  6. Output unique lines:

     sort -u file.txt
    
  7. Ignore case while sorting:

     sort -f file.txt
    
  8. Sort ignoring leading blanks:

     sort -b file.txt
    
  9. Write sorted output to a file:

     sort -o sorted.txt unsorted.txt
    

Additional Information

  • Help option:

      sort --help
    
  • View sort manual page:

      man sort
    

This cheatsheet covers the essential options and usage scenarios for the sort command. For more advanced features and details, refer to the man page or use sort --help.

0
Subscribe to my newsletter

Read articles from Cloud Tuned directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Cloud Tuned
Cloud Tuned