Wednesday, August 31, 2011

Finding stuff in Linux


So it's time for some Linux fun! chances are if you are a regular linux user that you used the find command before, but here we are gonna review this useful command and maybe you can learn something new :)

The basics

One of the most common searches you will be using is looking for a specific file name or even a pattern, you could try the locate command first but sometimes you get too many results back, or it may be a recent file that isn't yet in the locate database, so here is how a search by name using find would look like

find / -name myfile


/ being the path we want to start our search from, and of course 'myfile' the name of the file we want to find, we also could use a pattern for example if we wanted to find all mp3 file in our system...

find / -name '*.mp3'

so that's it for the basics, let's move on...

Searching by time

So let's say we just screwed up and unziped a large file into our current dir, and that left us with lot's of small files mixed with the stuff we had there before, so we would like to clear up this mess, find to the rescue!

We can use find to search for files created in the last 5min,

find . -cmin -5

There are different time searching switches, -Xmin and -Xtime, min being minutes and time being days, the X here refers to the file time attribute we want to use for our search, you can use this table:


Access Time | a

This is the time that the file was last accessed, read or written to.

Modify Time | m

This is the last time the actual contents of the file were last modified.

Change Time | c

This is the time that the inode information (permissions, name, etc., the metadata, as it were) was last modified.



For uncompressed files only the Change Time, actually changes, so that's why used that in this case.

Finally we can use the -exec option to execute a command on every file found, for example:

find . -cmin -10 -exec rm '{}' \;


Filtering by file type


For searching for specific file types, like directorys we can use the -type option, like this:

find /etc -type d

Here is a small table with some of the posible file types:

              d      directory
              f      regular file
              l      symbolic link; this is never true if the -L option or the -follow option is  in
                     effect, unless the symbolic link is broken.  If you want to search for symbolic
                     links when -L is in effect, use -xtype.


That's it for now! if you want to learn more about find, 'man find' is ur friend!


No comments:

Post a Comment