brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sort -c tells you if a file is sorted without sorting it

Linux
~/tips/tip-sort-c-check-sorted

sort -c file.txt

Checks whether the input is already sorted and names the first line that is out of order.

comm and join need sorted input, and when they get something else the output looks plausible and is wrong. Before I trust a result, I like to ask the file first.

sort -c file.txt

The manual describes -c as “check for sorted input; do not sort”. The lines a b d c, one per line, gave this on coreutils 9.4:

sort: s.txt:4: disorder: c

It names the file, the line number and the first line that breaks the order. The command exited with status 1. On a sorted file it prints nothing and exits with 0, so you can use it directly in a script:

sort -c names.txt && echo sorted || echo "sort it first"

-C (--check=quiet) is the same without the message: “like -c, but do not report first bad line”. It also exited with 1 on the unsorted file, and it is the one I’d use in a script that has its own error text.

Run the check with the same options you plan to use afterwards. A file can be in order for sort -n and out of order for plain sort, so sort -n -c and sort -c can give different answers on the same file. The same goes for -k, -t and the locale.

One caveat: -c reads the file but writes no sorted copy, so it does not fix anything. When it reports a disorder, run sort with the same options and write the result to a new file instead of over the old one.

Further reading: sort(1) manual, GNU coreutils: sort invocation

More Linux tips notify-send -r "$id" "Backup" "Done" pgrep -af 'sleep 301' smbstatus -L msmtp --serverinfo --tls --tls-certcheck=off --host=smtp.example.com --port=587 smbclient //server/share -U user -Tc backup.tar "*" All Linux tips (283) All topics

Link