86

私がテキストファイルを持っていると仮定します

alex
bob
matrix
will be removed
git repo

そして私はそれを更新しました

alex
new line here
another new line
bob
matrix
git

ここでは、行番号(2,3)を追加し、行番号(6)を更新しました。

git diffまたはその他のgitコマンドを使用してこれらの行番号情報を取得するにはどうすればよいですか?

4

13 に答える 13

88

git diff --statあなたが参照しているものをコミットしたときに得られる出力が表示されます。

git diff --stat

変更された行番号を正確に表示するには、

git blame -p <file> | grep "Not Committed Yet"

また、変更された行は、結果の終了括弧の前の最後の番号になります。しかし、クリーンな解決策ではありません:(

于 2011-11-24T16:19:01.740 に答える
29

差分から結果の行番号を計算するbash関数は次のとおりです。

diff-lines() {
    local path=
    local line=
    while read; do
        esc=$'\033'
        if [[ $REPLY =~ ---\ (a/)?.* ]]; then
            continue
        elif [[ $REPLY =~ \+\+\+\ (b/)?([^[:blank:]$esc]+).* ]]; then
            path=${BASH_REMATCH[2]}
        elif [[ $REPLY =~ @@\ -[0-9]+(,[0-9]+)?\ \+([0-9]+)(,[0-9]+)?\ @@.* ]]; then
            line=${BASH_REMATCH[2]}
        elif [[ $REPLY =~ ^($esc\[[0-9;]*m)*([\ +-]) ]]; then
            echo "$path:$line:$REPLY"
            if [[ ${BASH_REMATCH[2]} != - ]]; then
                ((line++))
            fi
        fi
    done
}

次のような出力を生成できます。

$ git diff | diff-lines
http-fetch.c:1: #include "cache.h"
http-fetch.c:2: #include "walker.h"
http-fetch.c:3: 
http-fetch.c:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix)
http-fetch.c:4:+int main(int argc, const char **argv)
http-fetch.c:5: {
http-fetch.c:6:+       const char *prefix;
http-fetch.c:7:        struct walker *walker;
http-fetch.c:8:        int commits_on_stdin = 0;
http-fetch.c:9:        int commits;
http-fetch.c:19:        int get_verbosely = 0;
http-fetch.c:20:        int get_recover = 0;
http-fetch.c:21: 
http-fetch.c:22:+       prefix = setup_git_directory();
http-fetch.c:23:+
http-fetch.c:24:        git_config(git_default_config, NULL);
http-fetch.c:25: 
http-fetch.c:26:        while (arg < argc && argv[arg][0] == '-') {
fetch.h:1: #include "config.h"
fetch.h:2: #include "http.h"
fetch.h:3: 
fetch.h:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix);
fetch.h:4:+int main(int argc, const char **argv);
fetch.h:5: 
fetch.h:6: void start_fetch(const char* uri);
fetch.h:7: bool fetch_succeeded(int status_code);

このような差分から:

$ git diff
diff --git a/builtin-http-fetch.c b/http-fetch.c
similarity index 95%
rename from builtin-http-fetch.c
rename to http-fetch.c
index f3e63d7..e8f44ba 100644
--- a/builtin-http-fetch.c
+++ b/http-fetch.c
@@ -1,8 +1,9 @@
 #include "cache.h"
 #include "walker.h"
 
-int cmd_http_fetch(int argc, const char **argv, const char *prefix)
+int main(int argc, const char **argv)
 {
+       const char *prefix;
        struct walker *walker;
        int commits_on_stdin = 0;
        int commits;
@@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv, const char *prefix)
        int get_verbosely = 0;
        int get_recover = 0;
 
+       prefix = setup_git_directory();
+
        git_config(git_default_config, NULL);
 
        while (arg < argc && argv[arg][0] == '-') {
diff --git a/fetch.h b/fetch.h
index 5fd3e65..d43e0ca 100644
--- a/fetch.h
+++ b/fetch.h
@@ -1,7 +1,7 @@
 #include "config.h"
 #include "http.h"
 
-int cmd_http_fetch(int argc, const char **argv, const char *prefix);
+int main(int argc, const char **argv);
 
 void start_fetch(const char* uri);
 bool fetch_succeeded(int status_code);

追加/削除/変更された行のみを表示し、周囲のコンテキストは表示したくない場合は、-U0gitdiffに渡すことができます。

$ git diff -U0 | diff-lines
http-fetch.c:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix)
http-fetch.c:4:+int main(int argc, const char **argv)
http-fetch.c:6:+       const char *prefix;
http-fetch.c:22:+       prefix = setup_git_directory();
http-fetch.c:23:+
fetch.h:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix);
fetch.h:4:+int main(int argc, const char **argv);

ANSIカラーコードに対して堅牢であるため、--color=alwaysgit diffに渡して、追加/削除された行の通常のカラーコーディングを取得できます。

出力は簡単にgrepすることができます:

$ git diff -U0 | diff-lines | grep 'main'
http-fetch.c:4:+int main(int argc, const char **argv)
fetch.h:4:+int main(int argc, const char **argv);

あなたの場合git diff -U0は次のようになります。

$ git diff -U0 | diff-lines
test.txt:2:+new line here
test.txt:3:+another new line
test.txt:6:-will be removed
test.txt:6:-git repo
test.txt:6:+git

行番号だけが必要な場合は、echo "$path:$line:$REPLY"をjustに変更しecho "$line"、出力を。にパイプしますuniq

于 2012-08-29T13:48:55.987 に答える
22

--unified=0のオプションを使用しますgit diff

たとえばgit diff --unified=0 commit1 commit2、diffを出力します。

*ここに画像の説明を入力してください*

オプションがあるため--unified=0、diff出力には0個のコンテキスト行が表示されます。つまり、変更された行を正確に表示します。

これで、「@@」で始まる行を識別し、パターンに基づいて解析できます。

@@ -startline1,count1 +startline2,count2 @@

上記の例に戻ると、WildcardBinding.javaファイルの場合、行910から開始し、0行が削除されます。行911から開始し、4行が追加されます。

于 2014-07-18T03:58:47.513 に答える
7

これと同じ問題が発生したため、git diffの出力を変更して、各行の行番号を付加するgawkスクリプトを作成しました。作業ツリーを比較する必要がある場合は、それに限定されませんが、便利な場合があります。多分それはここの誰かに役立ちますか?

$ git diff HEAD~1 |showlinenum.awk
diff --git a/doc.txt b/doc.txt
index fae6176..6ca8c26 100644
--- a/doc.txt
+++ b/doc.txt
@@ -1,3 +1,3 @@
1: red
2: blue
 :-green
3:+yellow

ここからダウンロードできます:
https ://github.com/jay/showlinenum

于 2014-05-20T05:48:41.403 に答える
4

コミットされていないすべての行の行番号(追加/変更):

git blame <file> | grep -n '^0\{8\} ' | cut -f1 -d:

出力例:

1
2
8
12
13
14
于 2016-02-25T09:33:12.030 に答える
2

行番号を表示する外部差分ツールを構成します。たとえば、これは私のgitグローバル設定にあるものです:

diff.guitool=kdiff3
difftool.kdiff3.path=c:/Program Files (x86)/KDiff3/kdiff3.exe
difftool.kdiff3.cmd="c:/Program Files (x86)/KDiff3/kdiff3.exe" "$LOCAL" "$REMOTE"

詳細については、この回答を参照してください:https ://stackoverflow.com/q/949242/526535

于 2011-11-24T16:34:06.600 に答える
2

これが私が一緒に石畳にしたbash関数です:

echo ${f}:
for n in $(git --no-pager blame --line-porcelain $1 |
        awk '/author Not Committed Yet/{if (a && a !~ /author Not Committed Yet/) print a} {a=$0}' |
        awk '{print $3}') ; do
    if (( prev_line > -1 )) ; then
        if (( "$n" > (prev_line + 1) )) ; then
            if (( (prev_line - range_start) > 1 )) ; then
                echo -n "$range_start-$prev_line,"
            else
                echo -n "$range_start,$prev_line,"
            fi
            range_start=$n
        fi
    else
        range_start=$n
    fi
    prev_line=$n
done
if (( "$range_start" != "$prev_line" )) ; then
    echo "$range_start-$prev_line"
else
    echo "$range_start"
fi

そして、それは次のようになります:

views.py:
403,404,533-538,546-548,550-552,554-559,565-567,580-582
于 2012-11-29T23:13:58.860 に答える
2

パラメータとgit diff組み合わせて使用​​すると、変更された行数を表示するだけ済みます。shortstat

最後のコミット以降に変更された行数(すでにリポジトリにあるファイル内)

git diff HEAD --shortstat

次のようなものが出力されます

1 file changed, 4 insertions(+)
于 2013-12-01T07:47:31.180 に答える
1

これはおそらく、変更された行のかなり正確な数です。

git diff --word-diff <commit> |egrep '(?:\[-)|(?:\{\+)' |wc -l

また、diffの行番号の解決策は次のとおりです:https ://github.com/jay/showlinenum

于 2014-06-26T02:20:35.713 に答える
0

正確にはあなたが求めていたものではありませんが、git blame TEXTFILE役立つかもしれません。

于 2011-11-24T17:05:36.630 に答える
0

gitdiffを使ってファイルごとに変更された行だけを出力する方法を探していました。私のアイデアは、タイプチェックのためにこの出力をリンターにフィードすることでした。これが私を助けたものです

于 2019-12-21T16:32:51.547 に答える
0

この質問に出くわした場合に備えて、変更/削除された行の行番号を取得するためのPythonコピーパスタをいくつか示します。

変更および追加された行番号も取得するものに変更するのはかなり簡単なはずです。

私はWindowsでのみテストしましたが、クロスプラットフォームでもあるはずです。

import re
import subprocess

def main(file1: str, file2: str):
    diff = get_git_diff(file1, file2)
    print(edited_lines(diff))

def edited_lines(git_diff: str):
    ans = []
    diff_lines = git_diff.split("\n")
    found_first = False
    # adjust for added lines
    adjust = 0
    # how many lines since the start
    count = 0
    for line in diff_lines:
        if found_first:
            count += 1
            if line.startswith('-'):
                # minus one because count is 1 when we're looking at the start line
                ans.append(start + count - adjust - 1)
                continue

            if line.startswith('+'):
                adjust += 1
                continue

        # get the start line
        match = re.fullmatch(r'@@ \-(\d+),\d+ \+\d+,\d+ @@', line)
        if match:
            start = int(match.group(1))
            count = 0
            adjust = 0
            found_first = True

    return ans


def get_git_diff(file1: str, file2: str):
    try:
        diff_process: subprocess.CompletedProcess = subprocess.run(['git', 'diff', '--no-index', '-u', file1, file2], shell=True, check=True, stdout=subprocess.PIPE)
        ans = diff_process.stdout
    # git may exit with 1 even though it worked
    except subprocess.CalledProcessError as e:
        if e.stdout and e.stderr is None:
            ans = e.stdout
        else:
            raise

    # remove carriage at the end of lines from Windows
    ans = ans.decode()
    ans.replace('\r', '')
    return ans


if __name__ == "__main__":
    main("file1.txt", "file2.txt")
于 2020-05-07T09:15:14.313 に答える
0

おそらくこれは、クレジットがJakub Bochenskiに送られます-行番号付きのGit差分(行番号付きのGitログ)

git diff --unified=0 | grep -Po '^\+\+\+ ./\K.*|^@@ -[0-9]+(,[0-9]+)? \+\K[0-9]+(,[0-9]+)?(?= @@)'

于 2021-04-22T15:30:49.400 に答える