From 7eb542d1747da02019bc60f26c7a03c2471b2186 2008-04-15 15:03:37 From: Ville M. Vainio Date: 2008-04-15 15:03:37 Subject: [PATCH] SList.grep() supports optional 'field' argument --- diff --git a/IPython/genutils.py b/IPython/genutils.py index 1aa989f..09cc9ea 100644 --- a/IPython/genutils.py +++ b/IPython/genutils.py @@ -1052,25 +1052,40 @@ class SList(list): p = paths = property(get_paths) - def grep(self, pattern, prune = False): + def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. + If field is specified, the match must occur in the specified + whitespace-separated field. + Examples:: a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) + a.grep('chm', field=-1) """ + + def match_target(s): + if field is None: + return s + parts = s.split() + try: + tgt = parts[field] + return tgt + except IndexError: + return "" + if isinstance(pattern, basestring): pred = lambda x : re.search(pattern, x, re.IGNORECASE) else: pred = pattern if not prune: - return SList([el for el in self if pred(el)]) + return SList([el for el in self if pred(match_target(el))]) else: - return SList([el for el in self if not pred(el)]) + return SList([el for el in self if not pred(match_target(el))]) def fields(self, *fields): """ Collect whitespace-separated fields from string list @@ -1083,6 +1098,7 @@ class SList(list): a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] (note the joining by space). + a.fields(-1) is ['ChangeLog', 'IPython'] IndexErrors are ignored. diff --git a/doc/ChangeLog b/doc/ChangeLog index f5b621f..e440a63 100644 --- a/doc/ChangeLog +++ b/doc/ChangeLog @@ -1,3 +1,7 @@ +2008-04-15 Ville Vainio + + * genutils.py: SList.grep supports 'field' argument + 2008-04-09 Ville Vainio * deep_reload.py: do not crash on from __future__ import