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: comm --total counts the lines that differ between two sorted files

Linux
~/tips/tip-shell-comm-total-summary

comm --total a.txt b.txt

Adds a last line with how many lines are only in file one, only in file two, and in both.

I use comm to compare two lists, and then I always count the results by hand or pipe them into wc -l. GNU comm can do the counting itself.

comm --total a.txt b.txt

With two small sorted files, a.txt (apple, banana, cherry) and b.txt (banana, cherry, date, egg), the output looks like this. The columns are separated by tabs:

apple
		banana
		cherry
	date
	egg
1	2	2	total

The last line says: 1 line only in the first file, 2 only in the second, 2 in both. Same columns as the normal output, just counted.

It also works together with the column switches. comm --total -3 a.txt b.txt hides the lines both files share, but the totals line still counts them, so it printed 1 2 2 total again. That is handy when you only want to see the differences and still want to know how much matched.

If you don’t like tabs, --output-delimiter=STR picks another separator, for example comm --output-delimiter=' | ' a.txt b.txt.

The caveat is the same as for plain comm: both inputs must be sorted. Unsorted input gives wrong or confusing results, and GNU comm warns about it. If your lists are not sorted yet, use comm <(sort a.txt) <(sort b.txt). The --nocheck-order option only turns off the warning, it does not sort anything for you.

Further reading: comm invocation (GNU coreutils manual)

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