leah blogs

July 2013

07jul2013 · Summer of Scripts: g

What l is to file names, g is for file contents: A quick way to search by regular expressions:

g() {
  local p=$argv[-1]
  [[ -d $p ]] && { p=$p/; argv[-1]=(); } || p=''
  grep --exclude "*~" --exclude "*.o" --exclude "tags" \
    --exclude-dir .bzr --exclude-dir .git --exclude-dir .hg --exclude-dir .svn \
    --exclude-dir CVS  --exclude-dir RCS --exclude-dir _darcs \
    --exclude-dir _build \
    -r -P ${@:?regexp missing} $p
}

A popular incarnation would be, for example:

src/emacs-24.3% g '^main' src 
src/Makefile:maintainer-clean: distclean
src/makefile.w32-in:maintainer-clean: distclean
src/xrdb.c:main (int argc, char **argv)
src/Makefile.in:maintainer-clean: distclean
src/buffer.c:maintained internally by the Emacs primitives.  Enabling or disabling
src/emacs.c:main (int argc, char **argv)
src/tparam.c:main (int argc, char **argv)
src/termcap.c:main (int argc, char **argv)

As you can see, it filters some useless junk and again offers the ability to specify a different directory to search in as the last argument (just like l).

I use this all the time to navigate both foreign and my own source code. With a SSD, it’s plenty fast even on large file trees.

NP: Toxoplasma—Polizeistaat

Copyright © 2004–2022