Skip to content

~/avetyan.com/cheatsheets

Cheat sheets

sort and uniq cheat sheet

Sort lines by number, size, version or a single column, remove or count duplicates, and rank the most common values with sort and uniq.

3 min read


sort flags

FlagWhat it does

Sort by column

bash
sort -k2,2 file                         # by the second field
sort -k3,3n file                        # by the third field, numeric
sort -t, -k3,3nr data.csv               # CSV, column 3, numbers, descending
sort -t: -k3,3n /etc/passwd             # users by UID
sort -k2,2 -k1,1n file                  # by field 2, ties by numeric field 1
sort -k1.5,1.8 file                     # by characters 5–8 of field 1

Always write the end of the key (-k2,2). -k2 means “from field 2 to the end of the line”, which is rarely what you want.

Common sorts

bash
du -sh * | sort -h                      # sizes, smallest first
ls -l | sort -k5,5nr | head             # biggest files
sort -V versions.txt                    # 1.2, 1.9, 1.10
sort -u ips.txt > unique-ips.txt
sort -o file file                       # sort a file in place
LC_ALL=C sort big.txt > sorted.txt      # byte order: faster, repeatable

uniq

uniq only compares neighbouring lines, so sort first.

CommandPrints

Count and rank

bash
# most common lines first
sort file | uniq -c | sort -rn | head

# top 10 client IPs in an access log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10

# most used shell commands
history | awk '{print $2}' | sort | uniq -c | sort -rn | head

# duplicate lines across two files
sort a.txt b.txt | uniq -d

# remove duplicates but keep the original order
awk '!seen[$0]++' file

Keep in mind

  • sort order depends on the locale. With LC_ALL=C it compares bytes, which is faster and gives the same result on every server.
  • sort -n reads 1e3 as 1, and sort -g as 1000. Use -g for scientific notation.
  • sort file > file empties the file before reading it. Use sort -o file file.

Comments

Sign in with Google, GitHub or Facebook to comment.

Loading comments…