Bash functional: Difference between revisions
From wikinotes
(→Map) |
(→Map) |
||
Line 20: | Line 20: | ||
while read -r input; do | while read -r input; do | ||
"$ | "$@" "${input}" | ||
done | done | ||
} | } |
Revision as of 18:48, 11 December 2022
Filter
# filters out results not matching 'grep foo' find . \ | while read line; do \ echo $line | grep foo && echo "$line"; \ done
Map
map() { # ARGS: # $1: name of function to call # STDIN: the item to pass as argument to function local input while read -r input; do "$@" "${input}" done }Example
print_if_divisible_by_2() { # prints number if divisible by 2 [ $(($1 % 2)) -eq 0 ] && echo $1 } cat << EOF | map print_if_divisible_by_2 1 2 3 4 EOF #> 2 #> 4