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: uniq -d shows only the duplicate lines and uniq -u only the unique ones

Linux
~/tips/tip-linux-uniq-d-u-duplicates

sort hosts.txt | uniq -d

Find the entries that appear twice in a list, or the ones that appear once.

Removing duplicates is the job most people use uniq for. Two options turn it into a tool for finding them instead.

sort hosts.txt | uniq -d

-d prints one copy of every line that appears more than once, and nothing else. On a list of IP addresses or MAC addresses that should all be unique, an empty result is good news.

The opposite is -u:

sort hosts.txt | uniq -u

That prints only the lines that appear exactly once. I find it handy for comparing two lists quickly: cat a.txt b.txt | sort | uniq -u shows what is in one list but not in the other, as long as neither list has duplicates of its own.

The sort is not optional. uniq only compares each line with the line right before it, so duplicates that are not next to each other go unnoticed. That is the most common reason why uniq seems to do nothing.

Watch out for invisible differences too. A trailing space or a Windows line ending makes two lines different, so alice and alice both survive as unique. uniq -i ignores case, but for whitespace you have to clean the input first, for example with sed 's/[[:space:]]*$//'.

Further reading: GNU coreutils: uniq 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