Tuesday, January 1, 2013

How to search files in Ubuntu/Linux


1. Basic file search syntax

Ubuntu is using find command for search files in the file system.Basic syntax of search is follow below style


find [path] [expression]
where path is the path is the based directory where search need to be begins.If user not specify a path then find command starts to search file based on the currant directory where the terminal points.User can specify many expressions along with search patterns and actions for achieve many purposes as describe below.

2. Finding A File Based On File name

Let say for instance user wants to find a file named as "mytext.txt" in users home directories. (Case sensitive search)

$ find /home -name ‘mytext.txt’
Let say for instance user want to find all text files which has ".txt" suffix in users home directories. (Case sensitive search)
$ find /home -name ‘*.txt’
Let say for instance user want to find all text files which contains a string named as "tex" in users home directories. Following command search each and every file whether file name contains "tex" string.(Case sensitive search)

$ find /home -name ‘*tex*’
If user wants to search for all *.txt and *.avi files then it can be specify as follows.(Case sensitive search)
$ find /home -name ‘*.mpg’ -o -name ‘*.avi’
Case insensitive searches can be achieved by using the -iname phrase with the find command.


$ find /home -iname ‘*.mpg’

3. Adding Some More Functions to Search

Searching a entire file system causes to return thousands of files for a given file name .When user need to efficiently search file , Linux systems offer to specify search parameters to reduce the number of files return for a particular search.I show some examples below to demonstrate the search conditions.

Find all "mpg" files where size of each file greater then 700MB


$ find /home/ -name ‘*.mpg’ -a -size +700M
Find all "mpg" files which are modified within 15 days

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

4. Adding Some Actions

User is beneficial of searching files with conditions.But when user need something to do with the search files,Linux systems is capable of manipulating files along with the search.User may need to remove all files,move files ant etc which are output as search results.I have described below some actions which are perform on searched files.

Below command will search all "mpg" files which are modified within 15 days along with the size of each file is more than 700 MB and move it to new file location "/home/harsha/".


$ find /home/ -name ‘*.mpg’ -a -size +700M -mtime -15 -exec mv ‘{}’ /my/harsha/ \;
Note:The use of "{}" and \;(there should be a space before this)
‘{}’ matches the file that was found, while \; terminate the exec statement.

I mentioned only few ways of efficiently search a file in Ubuntu/Linux systems.But there are many conditions and actions can apply for a search.

No comments:

Post a Comment