问题
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 switch
o'`.
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
回答1:
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.
来源:https://stackoverflow.com/questions/57331099/git-grep-print-only-matching-pattern