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

前端 未结 5 2021
一个人的身影
一个人的身影 2020-12-22 15:25

Using Git, how could I search within all files in all local branches for a given string?

GitHub specific: is it possible to perform the above search across all GitHu

5条回答
  •  执笔经年
    2020-12-22 15:54

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

    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"
    

    Further:

    # 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"
    

提交回复
热议问题