33

How do I search all Git branches of a project for a file name?

I remember part of the filename (just the ending), so I'd like to be able to search for something like *_robot.php across all branches, and see which files match that. I'd preferably like to have it search history, and not just the HEADs of branches.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ben G
  • 26,091
  • 34
  • 103
  • 170
  • 2
    possible duplicate of [How can I search Git branches for a file or directory?](http://stackoverflow.com/questions/372506/how-can-i-search-git-branches-for-a-file-or-directory) – Robin Green Jun 29 '15 at 13:43

2 Answers2

36

This is one way:

git log --all --name-only --pretty=format: | sort -u | grep _robot.php
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • If you need to know the sha1 of the change, you can pass the 'before context' argument to grep, i.e. -B 100 git log --all --name-only --pretty=format: | sort -u | grep _robot.php -B 10 – Cory Dolphin Aug 20 '13 at 16:48
  • 2
    git log --all --name-only --pretty=format:'%H %f' | grep _robot.php -B 10 – hojin Jul 11 '18 at 02:32
9

Here is a simpler variation on @manojlds's solution: Git can indeed directly consider all the branches (--all), print the names of their modified files (--name-only), and only these names (--pretty=format:).

But Git can also first filter certain file names (regular expression) by putting the file name regular expression after the -- separator:

git log --all --name-only --pretty=format: -- <file_name_regexp> | sort -u

So, you can directly do:

git log --all --name-only --pretty=format: -- _robot.php | sort -u
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • Great, now how do I see the latest contents of that file? – ma11hew28 Dec 08 '12 at 01:15
  • 3
    You can for instance do `git log --all --name-only --pretty=format:%H -- | less` and look for the file name that you are interested in (by typing `/`, in `less`): the names of the modified files are preceded by their revision hash. (You then do the usual `git checkout ` in order to see the file.) – Eric O. Lebigot Dec 09 '12 at 13:27
  • 1
    Can you detail what does not work? I am confused about why it would not work, because this answer worked 3 years ago and still works with the current version of git, so I am not sure why it would fail for git 2.1.4, which was released in-between. – Eric O. Lebigot Jun 29 '15 at 23:23
  • even prettier: `git log --all --name-only --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' -- '**/blob*' | less` – ptim Jan 18 '16 at 02:19