Cleaning up deinstalled packages on Debian (and Ubuntu)

Disclaimer: this is for advanced users, use at your own risk.

If you run Debian on the same system for a while, packages get removed automatically and they never get purged. This means that config files and other useless cruft gets left over after many upgrades. I searched the web for an easy one-liner but didn't find one, so I hope this helps someone

See how many packages are in the 'deinstalled' state with this command:
Code:
dpkg --get-selections | grep deinstall | wc -l
To purge all of these packages at once:
Code:
dpkg --get-selections | grep deinstall | sed 's/deinstall/\lpurge/' | dpkg --set-selections; dpkg -Pa
I ran this on all of my systems and they've got a bit more free space now

Edit: For Ubuntu and others that use sudo:
Code:
dpkg --get-selections | grep deinstall | sed 's/deinstall/\lpurge/' | sudo dpkg --set-selections; sudo dpkg -Pa
aptitude --purge-unused purge packagename
And when you do apt-get autoremove you will still have stuff left over unless you do:
Code:
apt-get --purge autoremove