Git diff to show only lines that have been modified

前端 未结 7 1087
北恋
北恋 2020-12-04 08:10

When I do a git diff, it shows lines that have been added:

+ this line is added

lines that have been removed:

- this line i         


        
相关标签:
7条回答
  • 2020-12-04 09:03

    Here's another, simpler way to find only lines which have been modified, and hence begin with a single + or -, while retaining color output:

    git diff -U0 --color=always HEAD~ | grep --color=never -E $'^\e\[(32m\+|31m-)'
    
    1. The -U0 says to include 0 lines of context around the changed lines--ie: include just the changed lines themselves. See man git diff.
    2. The -E for grep allows it to work with extended regular expressions
    3. The $'' syntax apparently allows ANSI quoting, which properly interprets the ESC (escape, or 0x1b) character properly. See here.
    4. And here's the regex description from https://www.regex101.com:
    5. Basically, ^ matches the beginning of the line, \e matches the Escape char, which is the start of a color code in the terminal, \[ matches the next char in the color code, which is [, and then the (this|that) syntax matches "this" or "that", where "this" is 32m+, which is a green + line, and 31m- is a red - line.
    6. Colors are like this: \e[32m is green and \e[31m is red.
    7. + shows lines marked by git diff as added, of course, and - shows lines marked by git diff as deleted.
    8. Note that --color=never is required in the 2nd grep expression in order to prevent it from highlighting its matches, which would otherwise screw up the color codes coming in from git diff to the left.
    9. The + has to be escaped too as \+ because otherwise the + is a special regular expression (regex) character which specifies one or more occurrences of the preceding element. See here: https://en.wikipedia.org/wiki/Regular_expression#Basic_concepts.

    References:

    1. https://git-scm.com/docs/git-diff#_combined_diff_format
    2. Answer by @user650654: Git diff to show only lines that have been modified
    3. Answer by @wisbucky: Git diff to show only lines that have been modified

    Related:

    1. [my own answer] Git diff with line numbers (Git log with line numbers)
    2. [someone else's answer] Git diff with line numbers (Git log with line numbers)
    3. git diff with line numbers and proper code alignment/indentation
    4. git-filechange-search.sh - a script which allows you to search a file for a variable or function name and figure out which commits contain changes with that variable or function name. Ex. usage: ./git-filechange-search.sh path/to/my/file.cpp variable_name will find all commits with changes to file.cpp that contain variable_name in them. This is useful to see where and when certain features were changed. It's as though it were a search that could observe sections of a file displayed via git blame over time.
    0 讨论(0)
提交回复
热议问题