Finding Duplicate LaTeX Labels

Last night, as I was working on my dissertation, I noticed that LaTeX was giving me a warning message:

LaTeX Warning: There were multiply-defined labels.


Since LaTeX didn’t feel the need to tell me which labels were multiply-defined, I had to find them myself. As anyone who’s ever used LaTeX can tell you, finding them by hand in even a moderately complex document can be next to impossible. I wasn’t even sure if the the duplicates were in something I’d just added, or if they’d been there for a while. I didn’t even know how many duplicates there were.

Fortunately it’s easy to find duplicate LaTeX labels with a perl one-liner:

perl -nE 'say \$1 if /(\\label[^}]*})/' *.tex | sort | uniq -c | sort -n