Add to Favourites Add to Favourites    Print this Article Print this Article

Find specific code in all files of a certain type

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.

Was this answer helpful?

Also Read