Skip to content

Instantly share code, notes, and snippets.

@bfontaine
Created October 10, 2017 09:08
Show Gist options
  • Save bfontaine/aee3089b65c285d8deaf12bfda22f6a1 to your computer and use it in GitHub Desktop.
Save bfontaine/aee3089b65c285d8deaf12bfda22f6a1 to your computer and use it in GitHub Desktop.
Sort lines by some command

sort-by

Usage

cat ... | sort-by your command ...

Example

$ cat toto.jsons 
{"a": 1, "b": 2}
{"b": 1, "a": 3}
{"b": 3, "a": 5}
{"b": 0}

$ cat toto.jsons | sort-by 'jq .b'
{"b": 0}
{"b": 1, "a": 3}
{"a": 1, "b": 2}
{"b": 3, "a": 5}
#! /bin/bash -e
__sort_by() {
local sep="|" # arbitrary
local cmd="$*"
local tmpfile=$(mktemp)
local res=
while read line; do
res=$(echo "$line" | $cmd)
echo "$res$sep$line" >> $tmpfile
done
sort $tmpfile | cut "-d$sep" -f2
}
__sort_by $*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment