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 -t and -k sort a file on one column instead of the whole line

Linux
~/tips/tip-shell-sort-key-field

sort -t, -k3,3n people.csv

Sorts lines on one chosen column, as text or as numbers, instead of on the whole line.

Plain sort compares whole lines, starting at the first character. For a list of names that’s fine. For a CSV where the column I actually care about is the third one, it’s useless, and that’s where -t and -k come in.

-t tells sort what separates the fields, and -k says which field to sort on. Sorting a comma separated file numerically on its third column looks like this:

sort -t, -k3,3n people.csv

Read -k3,3n as: start at field 3, stop at field 3, compare as a number. You can stack keys to break ties. -k2,2 -k3,3nr sorts on the second column first and, inside each group, on the third column from high to low, because the r modifier only applies to that one key. The GNU manual has a nice one for /etc/passwd, which uses colons:

sort -t : -k 3,3n /etc/passwd

That lists every account ordered by user ID, so the system users end up on top and the real people further down. If the file has a header line, strip it first with tail -n +2, or the header gets sorted in between your data.

The caveat is the part after the comma. If you write -k3n without ,3, the key runs from field 3 to the end of the line. For text that often happens to look right, and for numbers it quietly doesn’t. When the order surprises you, add --debug: sort then underlines the part of each line it really used and warns you when a numeric key spans several fields. Also keep in mind that -t, splits on every comma. Sort doesn’t know CSV quoting, so a field like "Leiden, NL" counts as two fields. For files like that, my advice is to reach for a real CSV tool instead.

Further reading: GNU sort invocation

Going deeper: Moving on from hdtv: how to export your TV show list to Trakt.tv

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link