Tuesday, August 5, 2008

Unix Searching Tool -- find

The command "find" exists on almost all Unix. It is used for searching files. "find" can help you find files with specified attributes. In many conditions, "find" can work with other programmes well. Here I will take some examples to show the power of "find".

Suppose you have a directory named "shop" which contains many PHP files, but it contains some sub-directories, so you cannot use "ls *.php" to show all the PHP files. "find" can solve the problem:
find shop -name '*.php'
"find" searches all the sub-directores recursively and find all files whose names match the pattern "*.php" and print their paths. The argument "-name" means matching the filename.

If you need to calculate how many PHP files there are in the "shop" directory, just need use "wc" command to count the number of lines that "find" produced.
find shop -name '*.php' | wc -l
It proves that Unix "pipe" is very powerful and useful.

Beside matches file name, find can accept other conditions, for example, last modified time. In my computer, Tomcat (a JSP/Servlet container with a web server) generates log files on /var/log/tomcat5.5/. If I want to show the log files which are modified more than 2 days ago, I can use "-mtime" argument:
find /var/log/tomcat5.5/ -mtime +2
"-mtime" means "last modified time" and "+2" means "more than 2 days". Furthermore, I want to delete all the Tomcat log files which is generated more than 2 days ago. I can use "xargs" to combine "find" with "rm":
find /var/log/tomcat5.5/ -mtime +2 -print | xargs rm -f
"find" also supports logical operators. For the example above, if I need find the log files whose last modified time is more than 5 days or less than 3 days, I can use "find" as below:
find /var/log/tomcat5.5/ -mtime +5 -or -mtime -3.
"find" supports three logical operators: -not, -and, -or.

Certainly, the functions of "find" are too many to talk about. All the information about "find" can be finded by "man find", although it is not easy to read.

No comments: