Easiest way to do “git grep” for multiple strings?

I often need to search for lines containing multiple strings/patterns in a git project e.g.

git grep -i -e str1 --and -e str2 --and -e str3 -- *strings*txt

This gets tedious very quickly.

  • How do I extract the git commit ID used to make a zipped git archive?
  • Bitbucket branch management
  • How to use the throw away test branch strategy for syncing long lived feature branches?
  • Write Git commit message in new Vim window, then commit all within Vim
  • Git: Split subdirectory into repo and continue merging
  • Lost everything after deleting branch - nothing to commit (working directory clean)
  • Is there a better way to do this?

  • Maven Release-plugin “tag already exists” for nonexistant tag
  • Git remove certain commits from history, but keep their changes
  • Using git to Track changes to dropbox?
  • How to delete all git aliases at once?
  • How can I reset a diverged branch back to master
  • Moving entire git repo directory
  • 2 Solutions collect form web for “Easiest way to do “git grep” for multiple strings?”

    You didn’t mention what operating system you’re using, but if it’s linux-like, you can write a “wrapper” script. Create a shell script named something like git-grep1 and put it in a directory that’s in your $PATH, so git can find it. Then you can type git grep1 param1 param2... as if your script were a built-in git command.

    Here’s a quick example to get you started:

    # Example use:  find C source files that contain "pattern" or "pat*rn"
    # $ git grep1 '*.c' pattern 'pat*rn' 
    
    # Ensure we have at least 2 params: a file name and a pattern.
    [ -n "$2" ] || { echo "usage: $0 FILE_SPEC PATTERN..." >&2; exit 1; }
    
    file_spec="$1"  # First argument is the file spec.
    shift
    pattern="-e $1"  # Next argument is the first pattern.
    shift
    
    # Append all remaining patterns, separating them with '--and'.
    while [ -n "$1" ]; do
      pattern="$pattern --and -e $1"
      shift
    done
    
    # Find the patterns in the files.
    git grep -i "$pattern" -- "$file_spec"
    

    You’ll probably need to experiment with this, for instance, perhaps by enclosing the $file_spec and each pattern in single-quotes to prevent expansion by the shell.

    If you know the relative order of the strings, then you can do a

    git grep str1.*str2.*str3 -- *strings*txt
    
    Git Baby is a git and github fan, let's start git clone.