Unix grep, find and maxdepth
I’m writing this so I can find it next time I want to do this, and so my student programmers can more easily compare config settings across test sites.
Problem: Find a particular line quickly in a file in 7 different directories. In this case, it’s a Moodle config setting in 7 different installs, each with thousands of files.
Solution: With the help of this site, http://helpdesk.ua.edu/unix/tipsheet/tipv1n10.html I found a quick way to do it without traversing the thousands of files in each directory. The cheat is that I knew the config file in a Moodle install is always in the same spot. But I could leave maxdepth out.
The key here is that while I know
grep -r search_string *would work, it would take forever to go through all of those files, some of them quite large. I didn’t know how to get the recursive grep to only look at certain files. Turns out that is what backticks are for.
grep quiet `sudo find . -maxdepth 3 -type f -name config.php`./stage/moodle/config.php: $CFG->quiet_mode = TRUE;./ssctrunk/moodle/config.php:$CFG->quiet_mode = FALSE;./kai/moodle/config.php: $CFG->quiet_mode = TRUE;./videoannotation/moodle/config.php: $CFG->quiet_mode = TRUE;./test/moodle/config.php: $CFG->quiet_mode = TRUE;./coursemenu/moodle/config.php: $CFG->quiet_mode = TRUE;./joe/moodle/config.php: $CFG->quiet_mode = TRUE;
Quick Explanation:
- grep quiet – will search for the text “quiet” in the list of files produced by the command in backticks.
- sudo – to avoid being told I don’t have permission to see certain files.
- maxdepth – to only go 3 directories deep instead of recursing through everything. (I knew where the config.php file would be.)
- -type f -name config.php – only look at files named config.php. Ignore all others.