0 votes
1 view
in Devops and Agile by (20k points)

I have deleted a file or some code in a file sometime in the past. Can I grep in the content (not in the commit messages)?

A very poor solution is to grep the log:

git log -p | grep <pattern>

However, this doesn't return the commit hash straight away. I played around with git grep to no avail.

1 Answer

0 votes
by (28.4k points)

In order to search for commit content use the following command:

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

$ git rev-list --all | xargs git grep <expression> 

This command will work if you run into an "Argument list too long" error.

But, if in order to limit the search to some sub-tree (for instance, "lib/util"), pass that to the rev-list sub-command and grep as well:

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

This command will grep through all your commit text for regexp. Note that the reason for passing the path in both commands is because rev-list will return the revisions list where all the changes to lib/util happened, but also you need to pass to grep so that it will only search in lib/util.

Let us understand this better with the help of a scenario: grep might find the same <regexp> on other files which are contained in the same revision returned by rev-list (even if there was no change to that file on that revision).

Some other ways of searching your source are mentioned below:

A. Search working tree for text matching regular expression regexp:

$ git grep <regexp>

B. Search working tree for lines of text matching regular expression regexp1 or regexp2:

$ git grep -e <regexp1> [--or] -e <regexp2>

C. Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only:

$ git grep -e <regexp1> --and -e <regexp2>

D. Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2:

$ git grep -l --all-match -e <regexp1> -e <regexp2>

E. Search working tree for changed lines of text matching pattern:

$ git diff --unified=0 | grep <pattern>

F. Search all revisions for text matching regular expression regexp:

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

G. Search all revisions between rev1 and rev2 for text matching regular expression regexp:

$ git grep <regexp> $(git rev-list <rev1>..<rev2>)

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...