4

In the manual for grep, we have -o to print --only-matching patterns. Say echo foobar | grep foo would return foobar, but adding -o to grep would give only foo.

Many grep options like -P, -c, etc, can be used in conjunction with git to search through all files in the Git index. However, git grep -o PAT triggers an error: unknown switcho'`.

How can I print only matched string for each file in the Git index? i.e. "git grep -o PAT"

My trial:

for f in `git ls-files`; do grep -o PAT $f; done
  • You should avoid using old and deprecated back-tics, use parentheses like this: `for f in $(git ls-files); do grep -o PAT $f; done` https://stackoverflow.com/questions/4708549/what-is-the-difference-between-command-and-command-in-shell-programming – Jotne Aug 02 '19 at 20:07
  • Another workaround I used: `git grep PAT | grep -o PAT`. It's sometimes less to type. – Johannes Apr 20 '23 at 19:29

1 Answers1

5

git grep 2.18 doesn't have the option -o|--only-matching, git grep 2.19 has. If your version is lower than 2.19 you cannot use the option. To use it you have to upgrade.

phd
  • 82,685
  • 13
  • 120
  • 165