如何从 gif diff 中删除注释和信息行?

How to remove comments and information lines from gif diff?

当我发出如下命令时:

git diff -U10 C:\text1.c C:\text2.c 

我得到一个输出:

diff --git "a/C:\text1.c" "b/C:\text2.c"
--- "a/C:\text1.c"
+++ "a/C:\text2.c"
@@ -345,31 +456,32 @@ <content of the files>

如何去掉@@之前的这些行?我也尝试了选项 --color-word 但没有改变输出。

为了去掉 C 文件中的注释,我做了

git diff -G'(^[^\*# /])|(^#\w)|(^\s+[^\*#/])' -U10 C:\text1.c C:\text2.c 

如此处指定:How to make git diff ignore comments。但它不起作用。它不会删除对输出的任何评论。如何解决这两个问题?

如果你比较一对文件,第一个 @@ 行总是紧跟在第一个 +++ 行之后,不管输出的 header 部分是否是四个行:

$ git diff -U10 /tmp/[12]
diff --git a/tmp/1 b/tmp/2
index e4fbac4..624d841 100644
--- a/tmp/1
+++ b/tmp/2
@@ -1,2 +1,2 @@
 this is file
-one
+two

或更多:

$ chmod +x /tmp/2
$ git diff -U10 /tmp/[12]
diff --git a/tmp/1 b/tmp/2
old mode 100644
new mode 100755
index e4fbac4..624d841
--- a/tmp/1
+++ b/tmp/2
@@ -1,2 +1,2 @@
 this is file
-one
+two

因此,如果您有 sed,只需通过 sed '1,/^+++ /d'

如果您知道两个文件模式匹配(这样多余的行 old mode ...new mode ... 将不存在),您可以直接删除前四行。

(旁白:你的 git diff 只显示 header 行似乎很奇怪。 index ... 行应该出现甚至文件未存储在 Git.)

至于删除评论:Git 不知道某事是否是评论。注释语法特定于源语言。例如,# 在 shell 和 Python 中标记注释,但 // 在 C++ 和 Go 中标记注释。 (比这更复杂,因为在各种语言中还有其他类型的注释,并且有块数据结构——例如 Python 中的三重引号和 Go 中的反引号——可能会产生一些 看起来 像评论,实际上不是评论。)所以你需要为此发明自己的 detection-and-removal。