May 14, 2008

Notes on grep.

Usage

grep -ril "texttofind" *

-r : recursive
-i : ignore case
-l : show only the filenames

Search for dotfiles / hidden files

By default, grep skips .dotfiles. To include .dotfiles,

grep <search> * .*    # * searches non-dot files, and .* searches dot files

grep -r <search> .		# this will search all files, but must use "-r" and "."

Recursive

grep -r<...> "texttofind" .  # ". can be replaced with * but cannot have any file pattern/glob"

To restrict grep by file extension type,

grep -r --include "*.txt" TextToFind .

# note: grep ... *.txt won't work!  use --include

Regex

Alternative

Ag (silver searcher) is highly recommended. Ag is faster because it does better at ignoring files, while grep doesn’t ignore files well.

Misc notes

Older Gnu grep was slow (pre 2.7). Workaround http://rg03.wordpress.com/2009/09/09/gnu-grep-is-slow-on-utf-8/.

For those older grep, use:

alias grep='GREP_COLOR="1;37;45" LANG=C grep --color=auto'

References