I'm a frequent user of grep. I know that I can recursively search a directory using the -r flag:

// will recursively search all files
grep -r 'some string' *

However, if I want to limit my search to PHP files, the -r flag is suddenly useless:

// for some reason, this only searches the PHP files in the current dir
grep -r 'some string' *.php

Can anyone tell me a good way to recursively search a directory and its subdirs for a string but ONLY look at PHP or HTML files (and possibly TXT files too) ? I'm really hoping for a nice, short command that doesn't involve using an exclude file and which isn't really painful to type. I do this kind of search very frequently and have resorted to either searching EVERY file which is really slow (TAR and ZIP files really slow it down) OR typing repeated commands to search .php, /*.php, etc.

    ...and then write that into a shell function and add it to your startup scripts to save having to retype the whole thing every time.

      Thanks, BG. Sample output:

      [me@myserver somedir]# find ./ -iregex .+\.php$ -type f -print | xargs grep -il 'cc_1.php'
      ./account/user/account_colleges.php
      ./account_panel_on.php
      ./community/includes/functions_myplan.php
      
      etc...
      

      That works quite well, but the command is pretty hard to type. I use this command dozens of times an hour and am really hoping to streamline it. Also, I don't see how I can modify it to search a variety of file suffixes (php, php4, html, htm, txt, etc.).

      I'm wondering if I might create an alias for a command like this somehow? I.e., a command where I just supply 'some string' to a command and it does a recursive grep search which is limited to certain file types.

      Here are some other options I've discovered which also seem to work similar to your command:

      [me@myserver somedir]# grep -rl --include=*.php 'cc_1.php' *
      account/user/account_colleges.php
      account_panel_on.php
      community/includes/functions_myplan.php
      
      etc...
      

      another find command:

      [me@myserver test]# find * -name '*.php' -exec grep -l 'cc_1.php' {} \;
      account/user/account_colleges.php
      account_panel_on.php
      community/includes/functions_myplan.php
      
      etc...
      

        Ooops...just saw new posts...not sure how to make a bash alias. I'll be looking into that now. Tips welcome. Also welcome: any commentary on whether xargs or -exec or grep approach is better or what tradeoffs might be. If I enshrine this with bash alias, I'd like to do it right 😉

          Write a Reply...