# Cheat Sheet #day61 - sort

### `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

```sh
sort [OPTION]... [FILE]...
```

#### Common Options

* `-o FILE`: Write the output to FILE instead of standard output.
    
    ```sh
    sort -o sorted.txt unsorted.txt
    ```
    
* `-n`, `--numeric-sort`: Compare according to string numerical value.
    
    ```sh
    sort -n numbers.txt
    ```
    
* `-r`, `--reverse`: Reverse the result of comparisons.
    
    ```sh
    sort -r file.txt
    ```
    
* `-k FIELD`, `--key=FIELD`: Sort by a specific field. Fields are separated by tabs or spaces.
    
    ```sh
    sort -k 2 file.txt  # Sort by the second field
    ```
    
* `-t CHAR`, `--field-separator=CHAR`: Use CHAR as the field separator (default is whitespace).
    
    ```sh
    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.
    
    ```sh
    sort -u file.txt
    ```
    
* `-f`, `--ignore-case`: Fold lower case to upper case characters.
    
    ```sh
    sort -f file.txt
    ```
    
* `-u`, `--unique`: Output only the first of an equal run.
    
    ```sh
    sort -u file.txt
    ```
    
* `-b`, `--ignore-leading-blanks`: Ignore leading blanks.
    
    ```sh
    sort -b file.txt
    ```
    

#### Examples

1. **Sort lines in a file alphabetically:**
    
    ```sh
    sort file.txt
    ```
    
2. **Sort numerically:**
    
    ```sh
    sort -n numbers.txt
    ```
    
3. **Reverse the order:**
    
    ```sh
    sort -r file.txt
    ```
    
4. **Sort by the second field:**
    
    ```sh
    sort -k 2 file.txt
    ```
    
5. **Sort by a custom delimiter (e.g., comma):**
    
    ```sh
    sort -t, -k 1,1 file.txt
    ```
    
6. **Output unique lines:**
    
    ```sh
    sort -u file.txt
    ```
    
7. **Ignore case while sorting:**
    
    ```sh
    sort -f file.txt
    ```
    
8. **Sort ignoring leading blanks:**
    
    ```sh
    sort -b file.txt
    ```
    
9. **Write sorted output to a file:**
    
    ```sh
    sort -o sorted.txt unsorted.txt
    ```
    

#### Additional Information

* **Help option:**
    
    ```sh
    sort --help
    ```
    
* **View** `sort` manual page:
    
    ```sh
    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`.
