使用正则表达式让git diff忽略C语言注释不生效,该如何处理?
实现git diff忽略C语言注释的方案
前置说明
git自带的-G参数作用是筛选存在至少一行变更匹配正则的文件,不会过滤diff结果中的具体变更行,因此此前基于-G的尝试无法实现需求。可以通过以下方案实现目标:
方案1:单次使用直接过滤输出
适合临时需要忽略注释的场景,可同时处理单行//注释、单行/* */注释和跨行多行注释:
git diff -w master | awk ' BEGIN { in_comment = 0 } /^[+-].*\/\*/ { in_comment = 1 } /^[+-].*\*\// { if (in_comment) { in_comment = 0; next } } in_comment { next } !/^[+-].*\/\// { print } ' > text.diff
方案2:使用内置参数忽略纯注释变更块
如果仅需要忽略完全由注释组成的变更块(变更块内同时存在注释和业务代码时仍会正常显示),可直接使用git diff自带的-I/--ignore-matching-lines参数,适配你使用的2.17.1版本git:
git diff -w -I '^[[:space:]]*//' -I '^[[:space:]]*/\*.*\*/' master > text.diff
该方案无需额外后处理,执行效率更高。
方案3:配置全局别名方便长期使用
可将过滤规则配置为git全局别名,后续无需每次输入长命令:
- 执行以下命令添加别名:
git config --global alias.diff-nocom '!git diff "$@" | awk " BEGIN { in_comment = 0 } /^[+-].*\/\*/ { in_comment = 1 } /^[+-].*\*\// { if (in_comment) { in_comment = 0; next } } in_comment { next } !/^[+-].*\/\// { print } "'
- 后续使用时直接调用别名即可:
git diff-nocom master > text.diff
内容的提问来源于stack exchange,提问作者Veronika
相关产品推荐
相关产品推荐

