Skip to content

Instantly share code, notes, and snippets.

@kosugi
Created May 28, 2012 18:33
Show Gist options
  • Select an option

  • Save kosugi/2820542 to your computer and use it in GitHub Desktop.

Select an option

Save kosugi/2820542 to your computer and use it in GitHub Desktop.
sort command like elisp function sort-regexp-fields
# -*- coding: utf-8 -*-
#
# cat <<'EOD' | python sort-regexp-fields.py '[^;]+'
# using System;
# using System.Collections.Generic;
# using System.Web;
# using System.Web.UI;
# using System.Web.UI.WebControls;
# using System.Web.UI.HtmlControls;
# using System.Linq;
# EOD
import re
import sys
import getopt
def error(s):
sys.stderr.write(s)
sys.stderr.write('\n')
sys.exit(1)
def usage():
error('usage: %s [-r] key-extract-regex' % sys.argv[0])
def key(pattern, line):
m = pattern.search(line)
if m is None:
return line
elif m.groups():
return m.group(1)
else:
return m.group(0)
try:
opts, args = getopt.getopt(sys.argv[1:], 'r')
opts = dict([(k[1:], v) for k, v in opts])
except getopt.GetoptError:
usage()
if 1 <> len(args):
usage()
try:
pattern = re.compile(args[0])
sys.stdout.writelines(sorted(sys.stdin.readlines(), key=lambda line: key(pattern, line), reverse='r' in opts))
except re.error:
error('bad regex')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment