Git grep print only matching pattern

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

Upvotes: 4

Views: 2041

Answers (1)

phd
phd

Reputation: 95028

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.

Upvotes: 5

Related Questions