Find specific code in all files of a certain type


Enter Your Query:
Use '%' for wildcards and quotes for "exact phrases"


Top Level » System Level

Find specific code in all files of a certain typeLast Modified: Jan 17, 2013, 2:12 pm
If you're looking to find all files of a specific type, that contains a specific piece of code, you can do it by combining the find command with a grep of the text you're looking for.

For example, to find a specific string, lets call it asdfg in all php files, under the /home directory, use a script like this:

#!/bin/sh

#avoid special characters like quotes and brackets
STRING=asdfg

for i in `find . -name "*.php"`; do
{
       C=`grep -c --max-count=1 "$STRING" $i`
       if [ "$C" -gt 0 ]; then
               echo $i;

               #perl regex here, on $i, if needed
       fi
};
done;
exit 0;

If you need to get rid of the mentioned string, a sample perl regex would be:

perl -pi -e 's/asdfg//' $i

where it would find all instances of asdfg and replace it with "" (nothing), removing it from the files.

Note that a regex becomes more complicated if you need to replace special charcters.
Search with Google on how to use regular expressions for string swapping.

*** Always *** test your perl regex on a test file to ensure it works, before doing anything on mass to ensure you don't break anything.
 
Related Helpfiles
Finding files that have been modified within X days
Find all files of a certain type

2003 JBMC Software, Suite 173  3-11 Bellerose Drive, St Albert, AB  T8N 1P7  Canada.  Mon-Fri 9AM-5PM MST