find command and its usage
When working on Linux/UNIX OS, most of the times we will come across a situation where in we need to search for a specific file and perform various operations. find command is a very handy option in this situation and I will be posting about the find command with syntax and usage with examples.
find command
- basic general
syntax of the find command
syntax$ find <location> –name filename
- to find a file
by name “filename”
Command$ find / -name filename
Here the location is “/” which will search in
the entire filesystem. You can change this to desired location
- to find a file
which matching a specific pattern (all files with current PID $$)
Command$ find <location> -name *.$$
- to find a file
which doesn’t match a specific pattern ( ! does
the trick here)
Command$ find <location> ! -name *.$$
- to find a file
“file.$$” at a location “dbatmpdir” and display
contents of it ($$ == Process id).
Command$ find <location> -name file.$$ -exec cat {}
\;
Here 1. find command will find the file first
2. then give it as an argument to cat {}
which will execute it using “exec” and
3. \; is the syntax for completion.
Similarly to find a file matching specific
criteria and then delete it
(Here the criteria is *.$$ i.e. all files in
specific location (<location>) ending with pid $$)
Command$ find <location> -name *.$$ -exec rm {} \;
- find command
lists all types of files. To find only plain files matching a specific
pattern and then delete use -type
Command$ find <location> -type f -name *.$$ -exec rm
{} \;
- to find files
which are older than 7 days matching a specific pattern and then delete
use -type and -mtime
Command$ find <location> -type f -mtime +7 -name *.$$
-exec rm {} \;
- to grep for a pattern
in multiple files in current directory
Command$ find . -type f -name "*" -exec grep
-in "pattern" {} \;
- problem with
above command is, it prints all the matching lines but will never tell in
which file the match line exists. In order to print the file name add –print
to above command
Command$ find . -type f -name "*" -print
-exec grep -in "pattern" {} \;
- to find files of
specific pattern and copy them to different location
Command$ find . -name "*pattern*" -exec ls
{} \; 2>/dev/null | cpio -pdumv path