#!/usr/bin/env bash case "$0" in ( *egrep* ) grep="egrep" ;; ( *fgrep* ) grep="fgrep" ;; ( * ) grep="grep" ;; esac if [[ "$#" = "0" || "$1" = "-h" || "$1" = "--help" ]]; then cat <<-EOF usage: $0 [grep-args] [<.ext> ...] [ ...] Will use "grep" to search recursively through the given files or directories, which defaults to ".". ".svn" and ".git" directories are omitted. If an extension is given (a ".[^.]*" argument, possibly with (quoted) globs), then only files of these extension will be grepped. (Use "./.foo" for a path that begins with a a ".".) If named as something with "egrep" or "fgrep", will use these for searching. EOF exit fi grep_opts=($GREP_OPTIONS) pattern="" find_opts=() unset GREP_OPTIONS while getopts "VEFGPe:f:ivwxycLlm:oqsbHhnTuZA:B:C:aD:d:IrRUz" name; do if [[ "$name" = "e" ]]; then pattern="$OPTARG" elif [[ "${OPTARG+x}" = "x" ]]; then grep_opts+=( "-$name" "$OPTARG" ) else grep_opts+=( "-$name" ) fi done shift $(( OPTIND - 1 )) if [[ "x$pattern" = "x" ]]; then if [[ "$#" = "0" ]]; then echo "$0: missing pattern" 1>&2; exit 1 else pattern="$1"; shift fi fi fst_sfx="Y" while [[ "x$1" = "x."* && ! -e "$1" ]]; do if [[ "$fst_sfx" = "Y" ]]; then find_opts+=( "(" ); else find_opts+=( "-o" ); fi find_opts+=( "-name" "*$1" ); shift; fst_sfx="N" done if [[ "$fst_sfx" = "N" ]]; then find_opts+=( ")" ); fi # If there is a single null argument from an emacs `grep', drop it if [[ "$#" = "1" && "$TERM" = "emacs-grep" ]]; then case "$1__$(uname -s)" in /dev/null__* | NUL_CYGWIN* ) shift ;; esac fi # use "." if there are no arguments if [[ "$#" = "0" ]]; then set "."; fi # check that all of the rest are existing paths for i; do if [[ ! -e "$i" ]]; then echo "$0: missing path: $i" 1>&2; exit 1; fi done # if not a single path or if a directory, add -H to show file names # (before other flags so it can be can overriden) if [[ "$#" != "1" || -d "$1" ]]; then grep_opts=( "-H" "${grep_opts[@]}" ); fi # print paths with NUL separators, drop "./" if the only place is "." if [[ "x$*" = "x." ]]; then find_opts+=( "-printf" '%P\0' ) else find_opts+=( "-print0" ) fi # See also the values of emacs vars: # grep-find-ignored-directories, grep-find-ignored-files find "$@" "(" -name .svn -o -name .git -o -name CVS ")" -prune -o \ -type f "${find_opts[@]}" \ | sort -z \ | xargs -0 "$grep" "${grep_opts[@]}" -e "$pattern" -- \ | sed 's/\(.\{1999\}\).*/\1.../'