How to grep the git diff?

后端 未结 9 662
耶瑟儿~
耶瑟儿~ 2021-01-31 06:55

Is there a way to show the git-diff filtered by a given pattern.

Something like

git grepdiff pattern

changed file
+++ some sentence with pattern
change         


        
相关标签:
9条回答
  • 2021-01-31 07:16

    Not sure but isn't git diff -G <regex> flag OK?

    -G < regex>

    Look for differences whose added or removed line matches the given <regex>.
    
    0 讨论(0)
  • 2021-01-31 07:17

    I have been using this with great satisfaction :)

    grep -ri <MY_PATTERN> $(git diff 790e26393d --name-only) 
    
    0 讨论(0)
  • 2021-01-31 07:18

    Another possibility would be to view the whole diff and search the output using the normal less commands (type / and then the pattern).

    When you have less configured to show some lines before the match using --jump-target=N, this is pretty useful. Try it like this:

    PAGER="/usr/bin/less --jump-target=10" git diff
    

    This means that the match should be shown on line 10 (shows 9 lines of context above), which may be enough to also see the file name.

    You can also use e.g. --jump-target=.5 to make it position the match in the middle of the screen.

    0 讨论(0)
  • 2021-01-31 07:26

    I use git log -p, which opens less (configurable, though), which in turn can be searched for with /. There's also git log -S <searchword>.

    0 讨论(0)
  • 2021-01-31 07:32

    I think your approach to "grep" diff output is the best workaround.

    You may improve your awk script by using sed:

    colored="(^[\[[0-9;]*[a-zA-Z])"
    marker="^$colored+diff"
    pattern="^$colored+.*(\+|\-).*PATTERN"
    git diff --color | sed -rn -e "/$marker/! H; /$marker/ ba; $ ba; b; :a; x; /$pattern/ p"
    
    • colored: regex to match terminal colored lines
    • marker: marker to match division from differents diff hunks, lines starting with colored "diff"
    • pattern: pattern to search for, lines starting with colored "+" or "-" and containing "PATTERN"

    This will print full diff hunks, with added or removed PATTERN, also maintaining useful colored output.

    Note that ^[ in colored should be actual, literal ^[. You can type them in bash by pressing Ctrl + V, Ctrl + [

    0 讨论(0)
  • 2021-01-31 07:33

    Have you tried git diff -S<string> or git diff -G".*string.*"? Note that they are not equivalent, see the documentation about pickaxe for what -S does.

    0 讨论(0)
提交回复
热议问题