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 -u -k1,1 keeps one line per key instead of one per whole line

Linux
~/tips/tip-linux-sort-u-k-dedupe-by-key

sort -u -k1,1 logins.txt

Remove duplicates based on one column, like keeping one line per host name.

sort -u removes lines that are exactly the same. Combine it with a key and it removes lines that are the same in that column only, even when the rest of the line differs.

sort -u -k1,1 logins.txt

With this input:

alice 2025-01-03
alice 2025-01-05
bob 2025-01-04

you get one alice line and one bob line. The coreutils manual says that with -u, sort compares lines by the key only, and outputs the first of a run of lines that compare equal. -k1,1 limits the key to the first field; without the ,1 the key would run to the end of the line, and nothing would count as a duplicate.

For CSV, add the separator, as in sort -t, -u -k2,2 export.csv for one line per value in column two.

Which of the duplicates survives is the tricky part. It is the first one of each group in sorted order, and with -u on a key, the order within a group is the order of the input. So if you want the newest date per person, sort on the date first and only then dedupe on the name:

sort -k2,2r logins.txt | sort -s -u -k1,1

I’d add -s for a stable sort there, so the second sort keeps the order the first one made.

Further reading: GNU coreutils: sort invocation

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