patching grep to exclude directories from recursive search

I always wanted to be able to control which directory grep should go into and which it should not when I use the recursive (-r) option. I wanted a way to exclude some cache or other meaningless directories from it. I am using grep version 2.5.1 on gentoo linux (grep-2.5.1-r8).

I’ve just found a patch on the net that does exactly that! If you check this page: grep – Patches: patch #5051, Exclude Directories in Recursive… you can download a patch for the current grep version.

I’ll show you how to apply it on a gentoo distro. It’s really simple. I am assuming that you already use a portage overlay…say it lies inside your /usr/local/portage dir.

Lines that begin with “#” should be executed as root.
Lines that begin with “— COMMENT:” should be read and applied.


# mkdir -p /usr/local/portage/sys-apps/grep/files
# cp /usr/portage/sys-apps/grep/grep-2.5.1-r8.ebuild /usr/portage/sys-apps/grep/grep-2.5.1-r100.ebuild
# cp /usr/portage/sys-apps/grep/files/* /usr/local/portage/sys-apps/grep/files/
# vi /usr/portage/sys-apps/grep/grep-2.5.1-r100.ebuild
--- COMMENT: find the line that says KEYWORDS="alpha amd64 arm hppa ia64 m68k mips ppc ~ppc-macos ppc64 s390 sh sparc x86" and change it to: KEYWORDS="~x86" or your ~arch if it's another.
--- COMMENT: add this under src_unpack():
epatch “${FILESDIR}”/${PN}-2.5.1-exclude-dir.patch
# echo "=sys-apps/grep-2.5.1-r100 ~x86" >> /etc/portage/package/keywords
--- COMMENT: change ~x86 to your ~arch
--- COMMENT: download http://savannah.gnu.org/patch/download.php?file_id=9836 and save it as "grep-2.5.1-exclude-dir.patch"
# mv /path/to/grep-2.5.1-exclude-dir.patch /usr/local/portage/sys-apps/grep/files/
# cd /usr/local/portage/sys-apps/grep/
# ebuild grep-2.5.1-r100.ebuild digest
# emerge =sys-apps/grep-2.5.1-r100

and that’s it. The patch is applied cleanly (at least on ~x86) that I tried it and the result is this:

# mkdir -p ~/foo/bar
# mkdir -p ~/foo/zoo
# echo "test123" >> ~/foo/bar/test1.txt
# echo "test123" >> ~/foo/zoo/test2.txt
# cd ~/foo
# grep -r -n test123 *
bar/test1.txt:test123
zoo/test2.txt:test123
# grep -r test123 * --exclude-dir=zoo
bar/test1.txt:test123

enjoy :)