3

Is it possible with either diff/git (or other common utility) to produce diffs that contain only changes matching a pattern?

For example I have a file in two different versions:

a/file.txt

alpha
marker 100
omega

b/file.txt

start
marker 200
end

I would like to produce patch that contains only changes to lines containing marker string (or other regex pattern):

diff --git a/file.txt b/file.txt
index eb27e64..fcc1676 100644
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,3 @@
 alpha
-marker 100
+marker 200
 omega

(After applying such a patch, only the alpha->start, omega->end changes would still be pending.)

Right now I have a custom line-based processor with JGit, however I am very unhappy with my implmenetation, as I have to manually parse/split/recombine hunks, and generate diffs by copying/hacking JGit internal).

As this seems like a common use case, I would expect some tool to provide this out-of-the-box, but so far I haven't found anything.

Note that using things like git diff -G'marker' or any sort of hunk filtering is insufficient, as the hunk itself can be arbitrarily larger (e.g. here there is only one hunk containing the entire file change).

Peter Uhnak
  • 9,617
  • 5
  • 38
  • 51
  • You can set the context size of the diff hunk to zero, if you don't want to look at the context. Note, however, that `-S` and `-G` don't look at the *context* part of the lines in the first place, so I'm not sure what your gripe with `-G` is. – torek Feb 01 '21 at 11:38

0 Answers0