W
William Park
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
stdout.
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
expected.
For example,
a=(1 a 2 b 3 c)
func () { [[ $1 == [a-z] ]] && echo ".$1."; }
func x --> .x.
${a[*]| func } --> .a. .b. .d.
Ref:
http://freshmeat.net/projects/bashdiff/
http://home.eol.ca/~parkw/index.html#bash
help arrayfilter
help '${var|'
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
stdout.
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
expected.
For example,
a=(1 a 2 b 3 c)
func () { [[ $1 == [a-z] ]] && echo ".$1."; }
func x --> .x.
${a[*]| func } --> .a. .b. .d.
Ref:
http://freshmeat.net/projects/bashdiff/
http://home.eol.ca/~parkw/index.html#bash
help arrayfilter
help '${var|'