472,126 Members | 1,564 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,126 software developers and data experts.

(patch for Bash) list comprehension and filtering

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|'

--
William Park, Open Geometry Consulting, <op**********@yahoo.ca>
Toronto, Ontario, Canada
Jul 18 '05 #1
0 1627

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

35 posts views Thread by Moosebumps | last post: by
6 posts views Thread by William Park | last post: by
7 posts views Thread by Eelco Hoekema | last post: by
23 posts views Thread by Stan Cook | last post: by
1 post views Thread by Stelios Xanthakis | last post: by
18 posts views Thread by a | last post: by
4 posts views Thread by Gregory Guthrie | last post: by
reply views Thread by Kurt B. Kaiser | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.