VaTo
VaTo

Reputation: 3078

How can I search for a string that someone changed with git?

I would like to search for a specific string using git grep but I would like to filter the results by using git blame to know that the string I'm looking for was changed by a specific person.

I just don't know how can I combine them to get the results I want.

Thank you for your help.

Upvotes: 5

Views: 2072

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80931

This should do what you want.

author="Some User"
searchstring=string
searchfiles=(file1 file2 file3) # Leave empty for all files.

while IFS= read -rd '' file; read -rd '' nr; read -r line; do
    if git annotate -p -L "$nr,$nr" -- "$file" | grep -q "$author"; then
        printf '%s:%s:%s\n' "$file" "$nr" "$line"
    fi
done < <(git grep -nz "$searchstring" -- "${searchfiles[@]}")

Whether this works better/faster than Jonathan.Brink's answer is going to depend on the volume of matches for the line, the size of the history, where the author's commits live in the history, whether the change is in a more recent or less recent commit of the author's, etc.

Uses git grep -z to be safe for arbitrary file names and read -d '' to read those NUL-delimited fields.

Uses git annotate -L to limit lines that need annotation.

Output is the original git grep -n output but only for the author-matching lines.

Upvotes: 0

Jonathan.Brink
Jonathan.Brink

Reputation: 25383

You can write a little shell script to accomplish this:

git rev-list --author=Doe HEAD |
while read rev; do
    if git show -p $rev | grep "PATTERN" >/dev/null; then
        echo $rev
    fi
done

This will output the SHA's that are reachable by HEAD that have an author of "Doe" and have "PATTERN" in the commit content's.

Upvotes: 3

Related Questions