Essential OS Basics 2: Deleting files & folders in Linux

This series of posts will contain a list of some very useful Linux commands that you might need every now and then. This one is  a small tutorial on how to delete files in linux.
 First post on Linux networking here

1. Delete files and directories

rm command

Let us assume you want to delete some files in directory /usr/tmp . You first navigate to directory using command

cd /usr/tmp

Now if you want to delete a particular file use rm as following:

rm filename

or you can run following command from whichever directory you are in.

rm /usr/tmp/filename

But if you want to delete all the files in that directory, use rm as following:

rm *.*

To refine it further, if you want to delete only a few files but leave the rest, you’ll have to use wild-cards. I’ll explain it first using deleting by extension example. Let us assume that you have a collection of zip, mp3 and bin files (with extensions .zip, .mp3 and .bin respectively) and you want to delete only mp3 files, then execute :

rm *.mp3

It’ll delete all mp3 files file leaving all zip and bin files intact. But if you want to delete .bin files too, just add the extension like this:

rm *.mp3 *.bin

In order to delete directories, you have to modify it a little by adding -rf, If you have a directory named DIR which you want to delete, execute

rm -rf DIR

As posted earlier, you can use *.* wildcard to delete everything in the directory including all the sub-directories:

rm -rf *

Similarly you can delete files based upon their names too. Executing

rm a*.mp3

will delete all mp3 files which start with alphabet a, while

rm -rf a*

will delete every file and directory which starts with a

Apart from this, you might come across a scenario where you have to find and delete some type of files from multiple directories / folders. In this case I’m assuming that you need to delete all mp3 files located in various sub-folders inside /usr/tmp/. In such a case use find command

find /usr/tmp/ -type f -iname “mp3″ -delete

or

find /usr/tmp -type f -iname “mp3″ -exec rm -f {} ;

If you replace path /usr/tmp with just a / it’ll find and delete ALL mp3 files on your computer. So be careful

Useful links:

http://www.cyberciti.biz
www.linuxquestions.org

Leave a Reply