Files
oam/knowledge base/sort.md

1.8 KiB

Sort

Table of contents

  1. TL;DR
  2. Sort by the value in the last field
  3. Sources

TL;DR

# Sort given lines.
sort 'path/to/file'

# Sort lines in reverse.
sort -r 'path/to/file'

# Sort lines numerically.
sort -n 'path/to/file'

# Sort lines and remove duplicates.
sort -u 'path/to/file'

# Sort lines in random order.
sort -R 'path/to/file'

# Sort lines numerically according to the value in the 3rd column.
sort -t $'\t' -k 3n,3 'path/to/file'

# Sort by the value in the last field.
awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt \
| sort -n -t '|' | awk -F '|' '{print $NF}'

Sort by the value in the last field

  1. copy the last field (column) of each line at the beginning of each of the lines with a different delimiter:

    awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt
    
  2. sort on the 1st field specifing the delimiter to be the character above:

    awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|'
    
  3. discard the first field

    awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | awk -F '|' '{print $NF}'
    awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | awk -F '|' '{print $2}'
    awk 'BEGIN {FS=","; OFS="|"} {print $NF,$0}' file.txt | sort -n -t '|' | cut -d '|' -f 2
    

Sources