gpt4 book ai didi

git diff --ignore-matching-lines 忽略所有行

转载 作者:行者123 更新时间:2023-12-05 05:30:19 25 4
gpt4 key购买 nike

我正在尝试使用 git 的 --ignore-matching-lines,但遇到了一些奇怪的行为。这是普通 git diff 的输出:

$ git diff test.txt
diff --git a/test.txt b/test.txt
index 602c47d1cb..82655814c5 100644
--- a/test.txt
+++ b/test.txt
@@ -1,5 +1,7 @@
-Hello world
+Hello whitespace world
+

Lots of blank lines

Goodbye world
+

但是,如果我运行

$ git diff --ignore-matching-lines='^$' test.txt

没有输出

为什么忽略添加单词 whitespace 的更改?

最佳答案

这可能是由“$”本身的解释方式引起的,详见“How does git diff --ignore-matching-lines work”,作者 Sjoerd Langkemper (也是一个 Stack Overflow user ):

Git runs each regex over each line.
These lines end in a newline, so our regex is actually checked against:

His bill will hold more than his belican,\n

Where \n stands for a newline character.

When we have a change that adds an empty line, the regex is ran against a single byte string consisting of \n.
How do we match that?

It’s easier to use something like --ignore-blank-lines to ignore blank lines.

(顺便检查一下,git diff --ignore-blank-line 在您的特定情况下是否是一个不错的选择)

However, this does not work well together with other regular expressions that we want to ignore.
If we want to ignore a change that performs both an uninteresting belly-related change and adds an uninteresting empty line, our regular expressions we give to -I need to match both for the change to be hidden.
So we need a regular expression that matches an empty line, and --ignore-blank-lines and other white space related options don’t change that.

An empty line cannot be matched with ^$.

  • ^ matches both the beginning of the line and the beginning of the buffer.
  • Similarly, $ matches both the end of the line as the end of the buffer.

All changed lines end in a newline, just before the end of the buffer.
This means that ^$ matches every changed line.
The newline at the end starts a new line, and is immediately followed by the end of the buffer.

… his belican,\n

^ matches because \n starts a new line
$ matches because the buffer ends here

这可以解释为什么 --ignore-matching-lines='^$' 忽略了添加单词 whitespace 的更改:它忽略了 所有行!

To match more precisely, we can use \` to match the start of the buffer, and \' to match the end of the buffer.
An empty line can thus be matched with:

 \`\n\'

Where \n is an actual newline, not backslash-n.
This needs much escaping to enter correctly in a shell:

git diff -I $'\\`\n\\\'' …

关于git diff --ignore-matching-lines 忽略所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74733674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com