I would like to order results returned by git grep using some git-related criteria, for example the commit date.
Is there a way to do that?
Since you want to search the current worktree only, git log might be overkill. I haven't found a way to get git grep or something similar to output revision information, so it gets a bit complicated.
The snippet below greps for "test" in the current directory (subtree) and prints for each match:
Location (File:Line)
Commit hash
Date (committer)
Name (committer)
Commit Message
sort by file
word=test
git grep -nI "$word" | \
awk -F: '{printf $1" "$2" "; system("git blame \""$1"\" \"-L"$2","$2"\"")}' | \
awk '$3{print $1,$2,$3}' | \
while read -r file line hash; do \
echo -en "$file:$line " ; \
git show -s '--format=%h %ad %an %s' '--date=format:%Y-%m-%d_%H:%M:%S' "$hash" ; \
done | sort -V
sort by date
| sort -sk3r
show as table
git grep -nI "$word" | awk -F: '{printf $1" "$2" "; system("git blame \""$1"\" \"-L"$2","$2"\"")}' | awk '$3{print $1,$2,$3}' | while read -r file line hash; do echo -en "$file:$line\t" ; git show -s $'--format=%h\t%ad\t%cn\t%s' '--date=format:%Y-%m-%d_%H:%M:%S' "$hash" ; done | sort -V | sort -sk3r | column -ts $'\t' -o ' | '
This prints all matches of $word ("python" in this case) in the current directory together with commit data, sorted by date (newest first). Output:
$ git grep -nI python | awk ...
ceval_gil.c:1223 | 1ddfe593200 | 2025-06-20_04:23:38 | GitHub | msg 1
remote_debug.h:905 | 0909d6d8e89 | 2025-05-26_15:31:47 | GitHub | msg 2
remote_debug.h:917 | 0909d6d8e89 | 2025-05-26_15:31:47 | GitHub | msg 2
optimizer_symbols.c:21 | ec736e7daec | 2025-05-22_11:15:03 | GitHub | msg 3
crossinterp.c:14 | c81fa2b9cd1 | 2025-05-08_09:07:46 | GitHub | msg 4
initconfig.c:4576 | ac5424d6a9f | 2025-04-25_18:30:39 | GitHub | msg 5
git grepsearches the work tree, not the entire history.git grepsearches the current work tree, but that would be sufficient for me.sortorawkon the results ofgit grepand sort them on your ownfor commit in $(git log -S <pattern> --pretty=%H);do git grep <pattern> $commit;done. Extra options could be added togit logandgit grepto limit and format the output.