1881

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
  • 5
    possible duplicate of [How to grep git commits for a certain word](http://stackoverflow.com/questions/1337320/how-to-grep-git-commits-for-a-certain-word) –  Sep 05 '13 at 22:00
  • 3
    These blog posts by Junio C Hamano (git maintainer) might be interesting for you: * [Linus's ultimate content tracking tool](http://gitster.livejournal.com/35628.html) (about pickaxe search i.e. `git log -S` and blame) * [Fun with "git log --grep"][2] (searching commit messages) * [Fun with "git grep"][3] [2]: http://gitster.livejournal.com/30195.html [3]: http://gitster.livejournal.com/27674.html – Jakub Narębski May 28 '10 at 14:47
  • 1
    answer from possible duplicate actually works: https://stackoverflow.com/a/1340245/492 – CAD bloke Jun 02 '18 at 22:58
  • issue with this is that it doesn't give any context to the change.. i.e. who / when – Sonic Soul Jun 27 '18 at 15:01
  • 1
    I believe as of 2021, [VonC's answer](https://stackoverflow.com/a/2928721/1149924) is the only entirely correct one, and well deserves a green checkmark. – kkm inactive - support strike Jul 15 '21 at 05:54

21 Answers21

2407

To search for commit content (i.e., actual lines of source, as opposed to commit messages and the like), you need to do:

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

git rev-list --all | xargs git grep <expression> will work if you run into an "Argument list too long" error.

If you want to limit the search to some subtree (for instance, "lib/util"), you will need to pass that to the rev-list subcommand and grep as well:

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

This will grep through all your commit text for regexp.

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.

Just imagine the following 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).

Here are some other useful ways of searching your source:

Search working tree for text matching regular expression regexp:

git grep <regexp>

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

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

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

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

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>

Search working tree for changed lines of text matching pattern:

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

Search all revisions for text matching regular expression regexp:

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

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

git grep <regexp> $(git rev-list <rev1>..<rev2>)
Nickolay
  • 31,095
  • 13
  • 107
  • 185
Jeet
  • 38,594
  • 7
  • 49
  • 56
  • 4
    Excellent. +1. The GitBook add some details (http://book.git-scm.com/4_finding_with_git_grep.html), and Junio C Hamano illustrates some of your points: http://gitster.livejournal.com/27674.html – VonC May 28 '10 at 21:26
  • 18
    Unfortunately, I cannot get this going with msysgit-1.7.4. It tells me `sh.exe": /bin/git: Bad file number`. VonC's answer also works with msysgit. – eckes Jul 15 '11 at 08:46
  • 4
    If you get an "unable to read tree" error when you invoke git grep history with rev-list, you might need to clean things up. Try `git gc` or check out: http://stackoverflow.com/questions/1507463/how-to-deal-with-this-git-error – Anthony Panozzo Oct 28 '11 at 20:14
  • Can you also limit the `git grep` by choosing the directories to recurse down? – Ehtesh Choudhury May 16 '12 at 21:58
  • I've created a nice `alias` for this in my `~/.gitconfig`: `find = "!f() { git grep -C 2 $1 $(git rev-list --all); }; f"`. I used a shell function so I can pass the regexp to the alias. – asymmetric Jul 23 '12 at 14:28
  • 11
    Yeah, this seems to fail on Windows as well, alas. – mlissner Nov 28 '12 at 00:39
  • @Jeet would it make sense to replace all your `$(...)` with xargs calls so your examples will work more consistently (thanks @dlowe)? I got the same error as others on OSX: `bash: /usr/local/bin/git: Argument list too long` – hobs Apr 30 '13 at 16:55
  • 1
    Can I add git grep $(git rev-list --all) -- '*.txt' to search in a certain file type? – eighteyes Feb 21 '14 at 19:45
  • 3
    Another way with dealing with the `Argument list too long` issue is to: `git rev-list --all | (while read rev; do git grep -e $rev; done)` – Jeet Mar 05 '14 at 05:12
  • 2
    @Jeet Are there circumstances where this is a preferable option to the `git log -G` or `git log -S` answers? It seems to be much "heavier" in terms of processing as it's basically getting a list of commits, and then searching each individual commit? – Benjohn May 03 '15 at 09:10
  • 1
    @Benjohn I think there are differences in what is reported (log output vs. grep output, or patch contents vs. full file contents) that makes a difference in contexts in which one may be preferable to the other. – Jeet May 11 '15 at 05:53
  • This does not work: ```git grep $(git rev-list --all -- lib/util)``` It still returns results from the entire tree. – wmakley Jul 07 '16 at 22:27
  • @vmakley please see the updated reply here, that should work fine: http://stackoverflow.com/suggested-edits/3011778 – Ricardo Ferreira Mar 07 '17 at 10:54
  • What if I want to find something in the changed lines of the files in the working tree? And not in all the files in the project. – Iulian Onofrei May 24 '17 at 14:55
  • The answer to my previous question can be found [here](https://stackoverflow.com/a/47451180/865175). – Iulian Onofrei Jan 19 '18 at 14:07
  • For me, it does not work, when I'm not in the git root directory! I'm using Git 2.11. – mxmlnkn Mar 14 '18 at 18:20
  • I want to point out that I had scale issues with this solution, i ended up multiprocessing over a small set of small repositories, multiprocessing over revs in batches of 50, and running these jobs on the biggest servers I could find; `git grep` takes soo much longer and eats up much more cpu than `git log -S`. I think git-grep reconstructs every file for every revision and greps them, whereas git log only searches diffs. I still trust the results of git grpe all-revs, but unless i really need to know the search pattern did or did not exist, I will prefer git log for trivial searches – ThorSummoner May 08 '18 at 22:58
  • This does not work with git 2.21.0 on macos. No matter what expression is used, output is always empty. – oarfish Aug 22 '19 at 07:23
  • This is almost useless, when the change I want to find was 20 commits ago, then ALL of the 20 commits containing the change will show up over and over again. If then, 10 commits ago there was another change with the searched string, then it is almost impossible to find. Is there a way to search in the "diff" of the commits only (changed lines only) instead of the entire code body? – kajacx Apr 08 '20 at 08:29
  • I'm developing a tool based on this answer: https://github.com/GaetanoPiazzolla/git-search – Gaetano Piazzolla Sep 14 '20 at 07:37
  • Note - make sure your regexp is in single quotes i.e. `git grep 'y.rn' $(6c1418bb9a4c3e355s6ag1dfa6s5dgf1)` – Janac Meena Jun 03 '21 at 15:55
  • @kajacx I have the same question as yours "Is there a way to search in the "diff" of the commits only (changed lines only) instead of the entire code body?" Could anyone answer that question? – Brian Hong Aug 31 '21 at 14:26
  • 1
    I found it useful to limit the subtree by `$(git rev-list --after="2021-12-01" --all)` or `$(git rev-list --author="Shimon" --all)` – Shimon S Jan 11 '22 at 13:15
  • You propose to use a command with xargs, if an "argument too long" error occurs. What is the exact reason für the "argument too long" error? I could imagine something like "In shell xy, the evaluation of $() is not quoted according to zz, therefore all output of $() is written down in raw form". – user7427029 Oct 31 '22 at 10:14
  • This is the mother of all answers! :clap: – mdev Apr 04 '23 at 13:24
718

You should use the pickaxe (-S) option of git log.

To search for Foo:

git log -SFoo -- path_containing_change
git log -SFoo --since=2009.1.1 --until=2010.1.1 -- path_containing_change

See Git history - find lost line by keyword for more.

-S (named pickaxe) comes originally from a git diff option (Git v0.99, May 2005).
Then -S (pickaxe) was ported to git log in May 2006 with Git 1.4.0-rc1.


As Jakub Narębski commented:

  • this looks for differences that introduce or remove an instance of <string>. It usually means "revisions where you added or removed line with 'Foo'".

  • the --pickaxe-regex option allows you to use extended POSIX regex instead of searching for a string. Example (from git log): git log -S"frotz\(nitfol" --pickaxe-regex


As Rob commented, this search is case-sensitive - he opened a follow-up question on how to search case-insensitive.


Hi Angel notes in the comments:

Executing a git log -G<regexp> --branches --all (the -G is same as -S but for regexes) does same thing as the accepted one (git grep <regexp> $(git rev-list --all)), but it soooo much faster!

The accepted answer was still searching for text after ≈10 minutes of me running it, whereas this one gives results after ≈4 seconds ‍♂️.
The output here is more useful as well

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 3
    Thanks, I wasn't aware of this option. Looks like this is the best solution if you're interested in the commit messages and Jeet's solution is most appropriate if you need the traditional UNIX grep behavior of pure line matching. – Ortwin Gentz May 28 '10 at 21:20
  • 23
    Combine it with the `-p` flag to also output the diff. – Sander Jun 19 '14 at 10:42
  • Is there any way to exclude a all directories matching a specific patterns using git log -S? – BakaKuna Dec 18 '14 at 10:48
  • @BakaKuna why yes, there sure is (it uses the `--format` option though, not the `-S` option): http://stackoverflow.com/a/21079437/6309 – VonC Dec 18 '14 at 11:37
  • does this only search the history of the current branch, rather than commits throughout the whole repo history? – Anentropic Dec 10 '15 at 17:17
  • 5
    @Anentropic you would need the `--branches --all` options to search for the all repo. – VonC Dec 10 '15 at 20:35
  • @Jakub Narębski As soon as I try `--pickaxe-regex`, I get `fatal: bad revision ''`. Maybe give a concrete example. – U. Windl Feb 22 '20 at 00:56
  • @U.Windl I am not Jakub, but I have edited my answer to include an example. – VonC Feb 22 '20 at 09:47
  • Comparing this answer to the links within it confuses me: the `pickaxe (-S)` link jumps to an option that isn't called `pickaxe`, but `pickaxe-all`. Also, unlike the text of this link would suggest, `-S` and `pickaxe-all` are different (though related); the word `pickaxe` isn't even in the documentation for `-S`. And finally, it *does* look like `pickaxe-all` would usually be helpful for this task, yet neither of your examples use it. – Daniel Kaplan Sep 24 '22 at 00:00
  • 1
    @DanielKaplan Thank you for your feedback. I have edited the answer accordingly and removed any reference/link to `--pickaxe-all`. `-S` (`pickaxe`) is enough. – VonC Sep 24 '22 at 00:17
  • @VonC Cool and thanks. When I click on the new link it goes to a white page. I'm still confused about calling `-S` "pickaxe" though. The documentation doesn't call it that, as far as I can tell. – Daniel Kaplan Sep 24 '22 at 00:24
  • 1
    @DanielKaplan Which link is problematic? As for "pickaxe", it is the original name of the [`git diff -S` option](https://github.com/git/git/commit/52e9578985fb636ec1d3f6cf794fdadd5ec896fc). While the documentation does not mention "pickaxe", that is what `-S` implements. I have always known that option (`-S`) referenced as the "pickaxe option". – VonC Sep 24 '22 at 00:31
  • @VonC Nevermind.I'm not sure why but it rendered correctly the second time I tried – Daniel Kaplan Sep 24 '22 at 00:54
  • 1
    This should be the accepted answer. Let me be first to say that. Executing a `git log -G --branches --all` *(the `-G` is same as `-S` but for regexes)* does same thing as the accepted one, but it soooo much faster! The accepted answer was still searching for text after ≈10 minutes of me running it, whereas this one gives results after ≈4 seconds ‍♂️ The output here is more useful as well – Hi-Angel Nov 24 '22 at 07:38
  • 1
    @Hi-Angel Thank you very much for your feedback on that 12 years old answer. I have included your comment in the answer for more visibility. – VonC Nov 24 '22 at 09:17
329

My favorite way to do it is with git log's -G option (added in version 1.7.4).

-G<regex>
       Look for differences whose added or removed line matches the given <regex>.

There is a subtle difference between the way the -G and -S options determine if a commit matches:

  • The -S option essentially counts the number of times your search matches in a file before and after a commit. The commit is shown in the log if the before and after counts are different. This will not, for example, show commits where a line matching your search was moved.
  • With the -G option, the commit is shown in the log if your search matches any line that was added, removed, or changed.

Take this commit as an example:

diff --git a/test b/test
index dddc242..60a8ba6 100644
--- a/test
+++ b/test
@@ -1 +1 @@
-hello hello
+hello goodbye hello

Because the number of times "hello" appears in the file is the same before and after this commit, it will not match using -Shello. However, since there was a change to a line matching hello, the commit will be shown using -Ghello.

Tyler Holien
  • 4,791
  • 2
  • 19
  • 14
  • 2
    Is there a way to show the matching change context in the git log output? – Thilo-Alexander Ginkel Jul 07 '14 at 09:20
  • 15
    @Thilo-AlexanderGinkel - I usually just add the `-p` option to show a diff for each commit. Then when the log is opened in my pager, I search for whatever it is I'm looking for. If your pager is `less` and you `git log -Ghello -p`, you can type `/hello`, press `Enter`, and use `n` and `N` to find the next/previous occurrences of "hello". – Tyler Holien Jul 07 '14 at 13:54
  • 2
    I found an interesting issue with `-G` and Regex: If command line uses UTF-8 and the file you are looking at uses some ISO-Latin (8 bit) encoding, `.*` fails. For example, I have a change `Vierter Entwurf` -> `Fünfter Entwurf`, and while `'V.*ter Entwurf'` produces a match, `'F.*ter Entwurf'` does not. – U. Windl Feb 22 '20 at 01:08
84

git log can be a more effective way of searching for text across all branches, especially if there are many matches, and you want to see more recent (relevant) changes first.

git log -p --all -S 'search string'
git log -p --all -G 'match regular expression'

These log commands list commits that add or remove the given search string/regex, (generally) more recent first. The -p option causes the relevant diff to be shown where the pattern was added or removed, so you can see it in context.

Having found a relevant commit that adds the text you were looking for (for example, 8beeff00d), find the branches that contain the commit:

git branch -a --contains 8beeff00d
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Edward Anderson
  • 13,591
  • 4
  • 52
  • 48
  • 1
    Hi, these lines don't seem to work at all. My command is > git log -p --all -S 'public string DOB { get; set; } = string.Empty;' and every time I try to run it I get > fatal: ambiguous argument 'string': unknown revision or path not in the working tree. > Use '--' to separate paths from revisions, like this: > 'git [...] -- [...]' – user216652 Feb 18 '20 at 15:34
  • @user216652 For some reason the `'` quotes aren't grouping your search string together as a single argument. Instead, `'public` is the argument to `-S`, and it's treating the rest as separate arguments. I'm not sure what environment you're running in, but that context would be necessary to help troubleshoot. I'd suggest opening a separate StackOverflow question if needed to help you troubleshoot, with all the context of how your git command is being sent to the shell. It seems to me that it's getting sent through some other command? Comments here aren't the right place to figure this out. – Edward Anderson Feb 18 '20 at 19:29
  • JFYI if you need Perl regexps instead of the default `grep -E` regexps you can use `--perl-regexp` option – nponeccop Aug 30 '22 at 19:50
64

If you want to browse code changes (see what actually has been changed with the given word in the whole history) go for patch mode - I found a very useful combination of doing:

git log -p
# Hit '/' for search mode.
# Type in the word you are searching.
# If the first search is not relevant, hit 'n' for next (like in Vim ;) )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bartłomiej Skwira
  • 1,701
  • 1
  • 16
  • 24
38

Search in any revision, any file (Unix/Linux):

git rev-list --all | xargs git grep <regexp>

Search only in some given files, for example XML files:

git rev-list --all | xargs -I{} git grep <regexp> {} -- "*.xml"

The result lines should look like this: 6988bec26b1503d45eb0b2e8a4364afb87dde7af:bla.xml: text of the line it found...

You can then get more information like author, date, and diff using git show:

git show 6988bec26b1503d45eb0b2e8a4364afb87dde7af
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
29

I took Jeet's answer and adapted it to Windows (thanks to this answer):

FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt

Note that for me, for some reason, the actual commit that deleted this regex did not appear in the output of the command, but rather one commit prior to it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 2
    +1 -- and if you want to avoid hitting "q" after each find, add `--no-pager` to the git command at the end – cgp Mar 28 '12 at 14:04
  • 2
    Also, I would note that appending to a text file has the added advantage of actually displaying the matching text. (append to a text file using `>>results.txt` for those not versed in Windows piping... – cgp Mar 28 '12 at 14:08
  • 2
    And I thought bash's syntax is ugly :) – smido May 22 '18 at 14:43
18

For simplicity, I'd suggest using GUI: gitk - The Git repository browser. It's pretty flexible

  1. To search code:

    Enter image description here
  2. To search files:

    Enter image description here
  3. Of course, it also supports regular expressions:

    Enter image description here

And you can navigate through the results using the up/down arrows.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
watashiSHUN
  • 9,684
  • 4
  • 36
  • 44
12

Whenever I find myself at your place, I use the following command line:

git log -S "<words/phrases i am trying to find>" --all --oneline  --graph

Explanation:

  1. git log - Need I write more here; it shows the logs in chronological order.
  2. -S "<words/phrases i am trying to find>" - It shows all those Git commits where any file (added/modified/deleted) has the words/phrases I am trying to find without '<>' symbols.
  3. --all - To enforce and search across all the branches.
  4. --oneline - It compresses the Git log in one line.
  5. --graph - It creates the graph of chronologically ordered commits.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
surajs1n
  • 1,493
  • 6
  • 23
  • 34
  • 1
    "Whenever I find myself at your place, I feel the need to use git!" – Sebi Oct 21 '19 at 14:03
  • 1
    There is also flag `-G` for searching using a regular expression and `-i` to make the search case-insensitive. – Ainar-G Jan 30 '23 at 08:20
7

For anyone else trying to do this in Sourcetree, there is no direct command in the UI for it (as of version 1.6.21.0). However, you can use the commands specified in the accepted answer by opening Terminal window (button available in the main toolbar) and copy/pasting them therein.

Note: Sourcetree's Search view can partially do text searching for you. Press Ctrl + 3 to go to Search view (or click Search tab available at the bottom). From far right, set Search type to File Changes and then type the string you want to search. This method has the following limitations compared to the above command:

  1. Sourcetree only shows the commits that contain the search word in one of the changed files. Finding the exact file that contains the search text is again a manual task.
  2. RegEx is not supported.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dotNET
  • 33,414
  • 24
  • 162
  • 251
4

I was kind of surprised here and maybe I missed the answer I was looking for, but I came here looking for a search on the heads of all the branches. Not for every revision in the repository, so for me, using git rev-list --all is too much information.

In other words, for me the variation most useful would be

git grep -i searchString $(git branch -r)

or

git branch -r | xargs git grep -i searchString

or

git branch -r | xargs -n1 -i{} git grep -i searchString {}

And, of course, you can try the regular expression approach here. What's cool about the approach here is that it worked against the remote branches directly. I did not have to do a check out on any of these branches.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bob Makowski
  • 305
  • 2
  • 8
3

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

3

Inspired by the answer https://stackoverflow.com/a/2929502/6041515, I found git grep seems to search for the full code base at each commit, not just the diffs, to the result tends to be repeating and long. This script below will search only the diffs of each git commit instead:

for commit in $(git rev-list --all); do 
    # search only lines starting with + or -
    if  git show "$commit" | grep "^[+|-].*search-string"; then 
        git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
    fi  
done

Example output, the bottom git commit is the one that first introduced the change I'm searching for:

csshx$ for commit in $(git rev-list --all); do 
>     if  git show "$commit" | grep "^[+|-].*As csshX is a command line tool"; then 
>         git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
>     fi  
> done

+As csshX is a command line tool, no special installation is needed. It may
987eb89 2009-03-04 Gavin Brock Added code from initial release
Dichen
  • 358
  • 1
  • 2
  • 12
2

Jeet's answer works in PowerShell.

git grep -n <regex> $(git rev-list --all)

The following displays all files, in any commit, that contain a password.

# Store intermediate result
$result = git grep -n "password" $(git rev-list --all)

# Display unique file names
$result | select -unique { $_ -replace "(^.*?:)|(:.*)", "" }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • I like your answer, and can see where it is going, but it's not working on MacOS ```zsh: parse error near `-unique'` ``` – om-ha Oct 25 '21 at 21:34
  • Okay! I got it working https://stackoverflow.com/a/69714869/10830091 GOT I HATE BASH – om-ha Oct 25 '21 at 21:45
2

Okay, twice just today I've seen people wanting a closer equivalent for hg grep, which is like git log -pS but confines its output to just the (annotated) changed lines.

Which I suppose would be handier than /pattern/ in the pager if you're after a quick overview.

So here's a diff-hunk scanner that takes git log --pretty=%h -p output and spits annotated change lines. Put it in diffmarkup.l, say e.g. make ~/bin/diffmarkup, and use it like

git log --pretty=%h -pS pattern | diffmarkup | grep pattern
%option main 8bit nodefault
        // vim: tw=0
%top{
        #define _GNU_SOURCE 1
}
%x commitheader
%x diffheader
%x hunk
%%
        char *afile=0, *bfile=0, *commit=0;
        int aline,aremain,bline,bremain;
        int iline=1;

<hunk>\n        ++iline; if ((aremain+bremain)==0) BEGIN diffheader;
<*>\n   ++iline;

<INITIAL,commitheader,diffheader>^diff.*        BEGIN diffheader;
<INITIAL>.*     BEGIN commitheader; if(commit)free(commit); commit=strdup(yytext);
<commitheader>.*

<diffheader>^(deleted|new|index)" ".*   {}
<diffheader>^"---".*            if (afile)free(afile); afile=strdup(strchrnul(yytext,'/'));
<diffheader>^"+++".*            if (bfile)free(bfile); bfile=strdup(strchrnul(yytext,'/'));
<diffheader,hunk>^"@@ ".*       {
        BEGIN hunk; char *next=yytext+3;
        #define checkread(format,number) { int span; if ( !sscanf(next,format"%n",&number,&span) ) goto lostinhunkheader; next+=span; }
        checkread(" -%d",aline); if ( *next == ',' ) checkread(",%d",aremain) else aremain=1;
        checkread(" +%d",bline); if ( *next == ',' ) checkread(",%d",bremain) else bremain=1;
        break;
        lostinhunkheader: fprintf(stderr,"Lost at line %d, can't parse hunk header '%s'.\n",iline,yytext), exit(1);
        }
<diffheader>. yyless(0); BEGIN INITIAL;

<hunk>^"+".*    printf("%s:%s:%d:%c:%s\n",commit,bfile+1,bline++,*yytext,yytext+1); --bremain;
<hunk>^"-".*    printf("%s:%s:%d:%c:%s\n",commit,afile+1,aline++,*yytext,yytext+1); --aremain;
<hunk>^" ".*    ++aline, ++bline; --aremain; --bremain;
<hunk>. fprintf(stderr,"Lost at line %d, Can't parse hunk.\n",iline), exit(1);
jthill
  • 55,082
  • 5
  • 77
  • 137
1
git rev-list --all | xargs -n 5 git grep EXPRESSION

is a tweak to Jeet's solution, so it shows results while it searches and not just at the end (which can take a long time in a large repository).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
laktak
  • 57,064
  • 17
  • 134
  • 164
0

So are you trying to grep through older versions of the code looking to see where something last exists?

If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.

Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
  • 2
    Yes, but your "test" can be a script that greps for the code and returns "true" if the code exists and "false" if it does not. – Rob Di Marco Jun 01 '10 at 12:43
  • 2
    Well, what if code was bad in revision 10, become good in revision 11 and become bad again in revision 15... – Paolo Oct 29 '13 at 11:21
  • 2
    I agree with Paolo. Binary search is only appropriate for "ordered" values. In the case of git bisect, this means all "good" revisions come before all "bad" revisions, starting from the reference point, but that assumption can't be made when looking for transitory code. This solution might work in some cases, but it isn't a good general purpose solution. – Kent Mar 18 '14 at 15:17
  • 1
    I think this is highly inefficient as the whole tree is checked out multiple times for bisect. – U. Windl Feb 22 '20 at 01:20
0

Scenario: You did a big clean up of your code by using your IDE. Problem: The IDE cleaned up more than it should and now you code does not compile (missing resources, etc.)

Solution:

git grep --cached "text_to_find"

It will find the file where "text_to_find" was changed.

You can now undo this change and compile your code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Garytech
  • 328
  • 3
  • 6
0

A. Full, unique, sorted, paths:

# Get all unique filepaths of files matching 'password'
# Source: https://stackoverflow.com/a/69714869/10830091
git rev-list --all | (
    while read revision; do
        git grep -F --files-with-matches 'password' $revision | cat | sed "s/[^:]*://"
    done
) | sort | uniq

B. Unique, sorted, filenames (not paths):

# Get all unique filenames matching 'password'
# Source: https://stackoverflow.com/a/69714869/10830091
git rev-list --all | (
    while read revision; do
        git grep -F --files-with-matches 'password' $revision | cat | sed "s/[^:]*://"
    done
) | xargs basename | sort | uniq

This second command is useful for BFG, because it only accept file names and not repo-relative/system-absolute paths.

Check out my full answer here for more explanation.

om-ha
  • 3,102
  • 24
  • 37
0

Command to search in git history

git log -S"alter" --author="authorname" --since=2021.1.1 --until=2023.1.1 -- .
0

Another solution for the Windows and PowerShell is below:

git rev-list --all | ForEach-Object { git grep <expression> $_ }

You need to replace <expression> with your regular expression.

M S
  • 2,455
  • 1
  • 9
  • 11