Search for a pattern in a set of files using find and grep commands

A common task for developers is to search for a pattern amongst a bunch of files that are in different directories.

For instance, you are looking for the pattern “import sys” within a set of Python files. Those files are in sub directories mixed with other documents.

You can use the find command (to look for files ending with the py extension) and redirect those files to the grep command to search for the pattern “import sys” within all files found by the find command:

find . -name "*py" | xargs grep "import sys"

Note the double quotes and the use of the xargs command to scan the content of the files (not their names).

Of course, you can use all kind of wildcards:

find . -name "*py" | xargs grep "import sys"

Please follow and like us:
This entry was posted in Linux and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.