bash: how to delete elements from an array based on a pattern

前端 未结 6 1132
后悔当初
后悔当初 2020-12-03 07:26

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

6条回答
  •  北海茫月
    2020-12-03 08:11

    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[@]}`)
    

提交回复
热议问题