Say I have a bash array (e.g. the array of all parameters) and want to delete all parameters matching a certain pattern or alternatively copy all remaining elements to a new
I defined and used following function:
# Removes elements from an array based on a given regex pattern.
# Usage: filter_arr pattern array
# Usage: filter_arr pattern element1 element2 ...
filter_arr() {
arr=($@)
arr=(${arr[@]:1})
dirs=($(for i in ${arr[@]}
do echo $i
done | grep -v $1))
echo ${dirs[@]}
}
Example usage:
$ arr=(chicken egg hen omelette)
$ filter_arr "n$" ${arr[@]}
Output:
egg omelette
The output from function is a string. To convert it back to an array:
$ arr2=(`filter_arr "n$" ${arr[@]}`)