How to purge previously only removed packages?

I just found the following command which worked:

sudo apt-get purge $(dpkg -l | grep '^rc' | awk '{print $2}')

dpkg --get-selections | grep deinstall produces a list of package names with the word "deinstall":

$ dpkg  --get-selections | grep deinstall
account-plugin-windows-live         deinstall
debarchiver                         deinstall
flashplugin-installer               deinstall
    ...

By asking awk to print only the first field we get:

$ dpkg --get-selections | awk '$2 == "deinstall" {print $1}'
account-plugin-windows-live
debarchiver
flashplugin-installer
    ...

Now that we have the list of packages, xargs will let us feed the list of packages to a command (or commands, if the list is long enough):

dpkg --get-selections | awk '$2 == "deinstall" {print $1}' | xargs sudo apt-get purge --dry-run

When you are happy with the simulated results, remove --dry-run from the apt-get command.

Read:

for i in awk xargs apt-get ; do
    man $i
done

If you just want to purge the whole list, you can use this command; it will perform a dry run, in case essential packages are going to be removed, which you probably don't want to happen:

dpkg --get-selections | sed -n 's/\tdeinstall$//p' | xargs sudo apt-get --dry-run purge

If no essential package is going to be removed, it's safe to run the actual command:

dpkg --get-selections | sed -n 's/\tdeinstall$//p' | xargs sudo apt-get --yes purge
  • sed -n 's/\tdeinstall$//p': prints only lines in stdin where a tabulation followed by a deinstall string could be removed from the end of the line; this has the effect of printing only the lines containing a tabulation followed by a deinstall string at the end of the line without the actual tabulation followed by the deinstall string at the end of the line
  • xargs sudo apt-get --yes purge: passes each line in stdin as an argument to sudo apt-get --yes purge