Using git, how could I search for a string across all branches?

梦想与她 提交于 2019-12-02 13:52:01
manojlds

You can do this on a Git repo:

git grep "string/regexp" $(git rev-list --all)

Github advanced search has code search capability:

The Code search will look through all of the code publicly hosted on GitHub. You can also filter by:

  • the language: language:
  • the repository name (including the username): repo:
  • the file path: path:
teastburn

If you use @manojlds git grep command and get an error:

-bash: /usr/bin/git: Argument list too long" 

then you should use xargs:

git rev-list --all | xargs git grep "string/regexp"

Also see How to grep (search) committed code in the git history?

Zitrax

In many cases git rev-list --all can return a huge number of commits taking forever to scan. If you instead of searching through every commit on every branch in your repository history just want to search all branch tips you can replace it with git show-ref --heads. So in total:

git grep "string" `git show-ref --heads`

or:

git show-ref --heads | xargs git grep "string"

Tip: You can write output in file to view in editor.

nano ~/history.txt
git show-ref --heads | xargs git grep "search string here" >> ~/history.txt
hIpPy

There are few issues with the solutions listed here (even accepted).

  1. You do not need to list all the hashes as you'll get duplicates, also it takes more time.

It builds on this where you can search a string "test -f /" on multiple branches master and dev as

git grep "test -f /" master dev

which is same as

printf "master\ndev" | xargs git grep "test -f /"

So here goes.

This finds the hashes for the tip of all local branches and searches only in those commits.

git branch -v --no-abbrev | awk -F' *' '{print $3}' | xargs git grep "string/regexp"

If you need to search in remote branches too then add -a:

git branch -a -v --no-abbrev | awk -F' *' '{print $3}' | xargs git grep "string/regexp"

Update:

# search in local branches
git branch | cut -c3- | xargs git grep "string"
# search in remote branches
git branch -r | cut -c3- | xargs git grep "string"
# search in all (local and remote) branches
git branch -a | cut -c3- | cut -d' ' -f 1 | xargs git grep "string"

# search in branches, and tags
git show-ref | grep -v "refs/stash" | cut -d' ' -f2 | xargs git grep "string"

You can try this

git log -Sxxxx  #search all commits
git log -Sxxxx  --branches[=<pattern>]   #search branches
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!