Sunday, February 28, 2010

Using find to locate files

The GNU find command is a wonderful utility that can locate files on your Ubuntu system. The find command is part of the GNU findutils and is installed on every Ubuntu system.

The following paragraphs explain the basics of find .

The man pages show the syntax for using find as:

find [-H] [-L] [-P] [path...] [expression]

The optional flags [-H] [-L]
[-P] are not used commonly. They are useful only if your search want to follow
symbolic links. By default find command will not follow symbolic links.

The option [ path] refers to the location where your search should start.

The option [expression] refers to the way in which find should work.

Locating Files by Name

This seems to be the most common use of find. Try the following command on a terminal.

 $ find $HOME -name 'myfile.mp3' 

Note that I have quoted the name of the file to be found out. This must be made a habit, other wise you may get strange results ,especially when the file names have embeded spaces.

Find can accept wild cards like ? and * . If you wished to search for all of the mp3 files in your home directory, some of which you think might be named 'MP3' rather than 'mp3', you can run:

find $HOME -iname '*.mp3' 

The option -iname imposes case insensitivity on the search.

Locating Files by Size

Often you will look for big files in your home folder to save up some space . This can be done with

find $HOME -iname '*.mp3' -size +100M 

Other possible options with size are K and G for kilobytes and Giga bytes.

The above search can be modified to look for files less than 100MB as below.

find $HOME -iname '*.mp3' -type f -size -100M 

Locating Files by Access Time

It is also possible to locate files based on their access time or the time that they were last used, or viewed by the system. For example to show all files that have not been accessed in the $HOME directory for 30 days or more:

find $HOME -atime +30

You can combine various options to get better results. For example you can search for all mp3 files in the $HOME directory that have an access time of greater than 30 days:

find $HOME -iname '*.mp3' -atime +30

No comments: