You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Git代码库中搜索字符串并列出带最后提交日期的匹配项

Git 代码库中搜索字符串并显示对应行的最后提交日期

完全可以实现,这里给你两个直接可用的方案:

方案一:组合 grep + git blame(直观易理解)

先通过grep定位所有匹配字符串的文件和行号,再逐行调用git blame提取提交日期:

grep -n "print(" ./src | while read -r line; do
  file=$(echo "$line" | cut -d ":" -f1)
  lineno=$(echo "$line" | cut -d ":" -f2)
  commit_date=$(git blame -L $lineno,$lineno --porcelain "$file" | grep -m1 "^author-time" | cut -d " " -f2 | xargs -I {} date -d @{} +%Y-%m-%d)
  echo "$file   $commit_date"
done

命令解释:

  • grep -n:输出匹配行的文件名:行号:内容格式
  • while read:逐行处理grep的输出
  • git blame -L $lineno,$lineno --porcelain:只查看指定行的blame信息,--porcelain让输出格式更易解析
  • grep -m1 "^author-time":提取该行最后一次提交的时间戳
  • date -d @{} +%Y-%m-%d:把时间戳转成YYYY-MM-DD格式的日期

如果需要显示提交消息,把提取日期的那行替换为:

commit_msg=$(git blame -L $lineno,$lineno "$file" | head -n1 | sed 's/^.*) //')

方案二:用 git grep 替代 grep(更适配Git仓库)

Git自带的git grep仅搜索仓库追踪的文件(自动忽略.gitignore中的内容),配合git log获取提交信息更高效:

git grep -n "print(" -- ./src | while read -r line; do
  file=$(echo "$line" | cut -d ":" -f1)
  lineno=$(echo "$line" | cut -d ":" -f2)
  # 获取提交日期
  commit_date=$(git log -1 --format="%ad" --date=short -L $lineno,$lineno:"$file")
  echo "$file   $commit_date"
done

命令解释:

  • git grep -n:功能和普通grep类似,但只作用于Git管理的文件
  • git log -1 --format="%ad" --date=short -L $lineno,$lineno:"$file":仅显示指定行最后一次提交的日期(--date=short输出YYYY-MM-DD格式)
  • 若要显示提交主题,将%ad替换为%s即可

示例输出

运行命令后会得到符合需求的格式:

/src/file1.py   2024-05-06
/src/file5.py   2021-02-13
/src/file5.py   2021-10-01
/src/subdir/core.py   2025-01-03

内容的提问来源于stack exchange,提问作者Rabarberski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:37:39