Remove all unused kernels

As you know, everytime there is an update for the kernel, the new kernel is installed while the old one is not automaticaly uninstalled, after several kernel updates you will find a large list of old kernels in the start grub menu . So if we got no problem with the new installed kernel, we can just delete the old ones as they occupy space which is a wastage of resource.

Well there are multiple ways to find the kernel version:

Print the kernel release with uname:

$ uname -r

Print all the information related to kernel:

$ uname -a

List Linux Kernels with dpkg–debian package manager:

$ sudo dpkg -l | grep linux-headers | grep ii

$ sudo dpkg -l | grep linux-headers | grep ii | awk '{print $3}'

Well following is the magic command which removes unused kernels:

$ dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge

There is an extensive use of regular expressions and pipe characters which is very well explained below.