How to use find command

On Debian based distros, find is part of the package findutils. find allow one to search for files on a filesystem based on different condition, creation date, modified date, file size, file type, permissions, name ....
This tutorial, will be focused on finding files/directories based on their name, in order to explain in more depth the syntax of find, also will show how you can narrow down your search by adding condition on size and file modification time.

1. Find basis

The default syntax of find is as such:
find [path] [expression]
where path is the path used as root for searching pattern and expression the expression we want the file to match.

2. Finding a file based on filename

Let say for instance you want to find all .avi files in users home directories. Search files can be found with the following command:

# find /home -name '*.avi'
If you want to search for *.mpg and *.avi files, you will use the following:
find /home -name '*.mpg' -o -name '*.avi'
Case insensitive searches can be achieved by using the -iname switch:

find /home -iname '*.mpg' -o -iname '*.avi'

3. Adding some more criterias

Those kind of searches might returns far too many results, making it hard to find waht you were looking for in the first place.
Fortunately, you can narrow down the search by adding criteria such as the file size and the file modification date.
Let'search for .avi files bigger than 700M. This can be done with:

find /home/ -name '*.avi' -a -size +700M
Now, let's find the same subset of files that were modified less than 15 days ago:

find /home/ -name '*.avi' -a -size +700M -mtime -15

4. Adding some actions

Grand, we can now find files based on a subset of criteria. What would be even better is to apply some actions on those files. Action can be done with the use of -exec switch.
We can now find .avi file that are newer that 15 days, in this example, we are going to move those file to another location: /my/new/movies . I consider that this directory already exist on your system.
Moving .avi files bigger than 700M and younger than 15 days to /my/new/movies can be done with:

find /home/ -name '*.avi' -a -size +700M -mtime -15 -exec mv '{}' /my/new/movies/ \;
Mind the use of '{}' and  \; (there is a space before \;).
'{}' matches the file that was found, while  \; terminate the exec statement.


Popular posts from this blog

Como configurar el control de directv para que funcione con el Tv

Could not activate celullar data network - Iphone - Movistar

Show all values in Numpy array