Skip to content

Instantly share code, notes, and snippets.

@milo-minderbinder
Last active December 11, 2020 21:39
Show Gist options
  • Save milo-minderbinder/28d8a81bf2335dc51bec36cd24394c8f to your computer and use it in GitHub Desktop.
Save milo-minderbinder/28d8a81bf2335dc51bec36cd24394c8f to your computer and use it in GitHub Desktop.
sort git diff --stat by total number of lines changed (now with color!) (credit to jakub-g with the original solution: https://gist.github.com/jakub-g/7599177)
#!/usr/bin/env bash
# Any additional arguments are passed through to sort command.
# For example, you can order the sort by most changes to least by running with:
# > git-diff-stat-sort -r
# To pipe the output through the "less" command while preserving coloring, you can use:
# > git-diff-stat-sort -r | less -R
# Finally, to create a global git command alias, just run the following:
# > git config --global alias.diff-stat-sort '!git diff --stat --stat-width "$(tput cols)" --color=always | sort -t "|" -n -k2'
# The above alias will allow you to run the command without having to save/run the below command as a separate script,
# and instead, to just run it as a git subcommand. For example:
# > git diff-stat-sort
# or even:
# > git diff-stat-sort -r | less -R
git diff --stat --stat-width "$(tput cols)" --color=always | sort -t '|' -n -k2 "$@"
@milo-minderbinder
Copy link
Author

huh. Nevermind. found out the issue on my own. I think better fix is to change sort options to sort -k2 -t '|' -n, because there are a few problems with the existing method:

  1. sort does not treat consecutive white spaces as a single field separator, annoyingly
  2. the placement in the order for the summary line ("3 files changed, 13 insertions(+)...") could technically change depending on your locale specific settings and/or if the format of htat message changes.
  3. any spaces in filenames would mess up the sort order because it would change the key being used for comparison.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment