1

Is there a way I can dictate formatting to the output of git diff? When there are multiple files, I'd like some extra blank lines before each file start — that is, before each time it says

diff --git a/filename b/filename

This would help me spot the individual files. Right now I'm piping into BBEdit and then doing a global find-and-replace, and it's getting very old very fast. I don't really need to use a diff tool here, I think; I just want a little control over the text output. (Telling me how to pipe it through sed or something would probably be cool, though I was sort of hoping that git diff itself might accept some sort of formatting option.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • the sed way : [How do I insert a newline/linebreak after a line using sed](https://stackoverflow.com/a/11163357/86072) – LeGEC Jan 12 '22 at 17:33

1 Answers1

1

Here is an answer using sed and bash/zsh (as answered here) :

# include a '\' followed by a linefeed ('\n') in the replace pattern of sed :
git diff --cached | sed -e 's/^diff --git/'$'\\\ndiff --git/'

(note: the bash/zsh specific part of the command above lies in the syntax used to insert an actual \<lf> on the command line : $'\\\n' will translate to that in bash/zsh, but perhaps not in other shells -- e.g : cmd.exe or powershell. You may choose another way to insert a \<lf> in a sed pattern, for example by reading patterns from a file instead of the command line, or by choosing a shell specific way to insert those characters on the command line)


If you want to keep the colors displayed by git diff, one way to do so is :

git diff --cached --color=always |\
    # spot the escape sequence that sets "diff --git" in bold, and print it in the output
    sed -e 's/^\(..1m\)diff --git/'$'\\\n\\1diff --git/'
LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • That would definitely do (and I could modify to suit). Thanks, I really appreciate it! I'll wait a bit before accepting, in case other options come along. – matt Jan 12 '22 at 18:53
  • I think I'll do it that way and work out a git alias as a helper. – matt Jan 12 '22 at 22:26
  • @matt : another option could be to plug an external diff renderer as a difftool, but the sed option in your case seems much simpler. – LeGEC Jan 12 '22 at 22:53
  • Another way to get a literal newline, in ancient /bin/sh: `LF=$(echo)`. Then include `$LF` inside double quotes, e.g., `sed -e "s/^diff --git/\\${LF}diff --git/`". I use techniques like this a lot, e.g., `TAB=$'\t'` which can be replaced with something else if `$'...'` is not available. – torek Jan 13 '22 at 01:40
  • So in the end I made an alias from that: `bbdiff = "!f() { git diff $@ | sed -e 's/^diff --git/'$'\\\ndiff --git/' | bbedit; }; f"` – matt Jan 18 '22 at 02:53