Is it better to use git grep than plain grep if we want to search in versioned source code?

后端 未结 5 1841
温柔的废话
温柔的废话 2021-01-31 02:03

In a git repository, is there any difference/benefit using git grep over good old grep?
An example would be?

5条回答
  •  萌比男神i
    2021-01-31 02:23

    The main advantage of git grep is that it can find the patterns in the git repository, i. e. also in others than the current version of the source. This cannot be done using the standard grep of course. Also there are a lot more features in the git grep like pattern arithmetic (things like git grep -e pattern1 --and --not \( -e pattern2 -e pattern3 \)), tree search using glob (things like git grep pattern -- '*.[ch]' to search only in .c and .h files) and some more.

    Here's an example session for searching in an older revision:

    $ mkdir git-test                 # create fresh repository
    $ cd git-test/
    $ git init .
    Initialized empty Git repository in /home/alfe/git-test/.git/
    $ echo eins zwei drei > bla      # create example file
    $ git add bla                    # add and commit it
    $ git commit bla
    [master (root-commit) 7494515] .
     1 file changed, 1 insertion(+)
     create mode 100644 bla
    $ echo vier fuenf sechs > bla    # perform a change on that file
    $ git commit -m 'increase' bla   # commit it
    [master 062488e] increase
     1 file changed, 1 insertion(+), 1 deletion(-)
    $ git grep eins | cat            # grep for outdated pattern in current version
                                      # (finds nothing)
    $ git grep eins master^ | cat    # grep for outdated pattern on former version
                                      # finds it:
    master^:bla:eins zwei drei
    

提交回复
热议问题