(patch for Bash) list comprehension and filtering

William Park opengeometry at yahoo.ca
Mon Aug 2 10:22:56 CEST 2004

1.  Here is shell version of Python filter() for array.  Essentially,
    you apply a command on each array element, and extract only those
    elements which it returns success (0).  This is specialized form of
    list comprehension where you can contruct an array from another
    array, using some sort of test or filtering.

    Usage is
        arrayfilter [-a var] command array
    where 'command' is a function, shell script, or external executable,
    which takes one argument (ie. the array elements).  If 'command'
    return success (0), then print the element; and, if it fails
    (non-zero), then skip the element.  If -a option is given, then the
    output will be save into array variable 'var', instead of default

    For example,
        a=(1 a 2 b 3 c)
        func () { [[ $1 == [a-z] ]]; }

        arrayfilter func a              --> a b c
        arrayfilter -a b func a --> b[1]=a b[3]=b b[5]=c

2.  More generally, here is shell version of Python list comprehension.
    Idea is to apply some test or command on each array element, and
    collect the outputs as parameter expansion.  So, for each element of
    array variable 'var',
        ${var| command }
    will expand to the output of 'command' which takes one argument.  If
    'command' returns NULL, then that element is skipped.  Usage is very
    similar to other parameter expansion, and both '*' and '@' work as

    For example,
        a=(1 a 2 b 3 c)
        func () { [[ $1 == [a-z] ]] && echo ".$1."; }

        func x                  --> .x.
        ${a[*]| func }          --> .a. .b. .d.

    help arrayfilter
    help '${var|'

William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
Toronto, Ontario, Canada

More information about the Python-list mailing list