Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

Is it possible to perform a 'grep search' in all the branches of a Git project?

Is it possible to run git grep inside all the branches of a Git control sourced project? Or is there another command to run?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The question "How to grep (search) committed code in the git history?" recommends:

 git grep <regexp> $(git rev-list --all)

That searches through all the commits, which should include all the branches.

Another form would be:

git rev-list --all | (
    while read revision; do
        git grep -F 'yourWord' $revision
    done
)

You can find even more example in this article:

I tried the above on one project large enough that git complained about the argument size, so if you run into this problem, do something like:

git rev-list --all | (while read rev; do git grep -e <regexp> $rev; done)

(see an alternative in the last section of this answer, below)

Don't forget those settings, if you want them:

# Allow Extended Regular Expressions
git config --global grep.extendRegexp true
# Always Include Line Numbers
git config --global grep.lineNumber true

This alias can help too:

git config --global alias.g "grep --break --heading --line-number"

Update August 2016: R.M. recommends in the comments

I got a "fatal: bad flag '->' used after filename" when trying the git branch version. The error was associated with a HEAD aliasing notation.

I solved it by adding a sed '/->/d' in the pipe, between the tr and the xargs commands.

 git branch -a | tr -d * | sed '/->/d' | xargs git grep <regexp>

That is:

alias grep_all="git branch -a | tr -d * | sed '/->/d' | xargs git grep"
grep_all <regexp>

This is an improvement over the solution chernjie had suggested, since git rev-list --all is an overkill.

A more refined command can be:

# Don't use this, see above
git branch -a | tr -d * | xargs git grep <regexp>

Which will allow you to search only branches (including remote branches)

You can even create a bash/zsh alias for it:

# Don't use this, see above  
alias grep_all="git branch -a | tr -d * | xargs git grep"
grep_all <regexp>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...