Thursday, July 31, 2008

Searching for files with different extensions using a single “find” command.

The find command is used to search the files in a directory. You can either mention the particular file name or use the wild card character “*”. So if you have to search for all the “. cpp” files recursively in a directory , the find command will be :

find . –name “*.cpp”

This command will give the path ( relative with reference to the current directory) of files with extension “.cpp”.

The find command together with “–exec”, can be used to perform different operations on the files. e.g. If you wish to search for a particular pattern in all “.h” files in a directory recursively, you can use combination of find and grep command as shown below.

find . –name “*.h” –exec grep –l “” {} \;

Here the output of find command which is nothing but the relative path of the “.h” files will be given to the grep command, thus giving the required result.

Here if you wish to search for the pattern in “*.cpp” as well as “*.h” files, you can use “–o” option as shown below:

find . –name “*.cpp” –o –name “.h” | xargs grep –l

Note: This “–o” option is available only with the GNU version of find.


No comments:

Search

My Blog List