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

Viewed 30240

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 array. Alternatively, the other way round, keep elements matching a pattern.

An example for illustration:

x=(preffoo bar foo prefbaz baz prefbar)

and I want to delete everything starting with pref in order to get

y=(bar foo baz)

(the order is not relevant)

What if I want the same thing for a list of words separated by whitespace?

x="preffoo bar foo prefbaz baz prefbar"

and again delete everything starting with pref in order to get

y="bar foo baz"
6 Answers

Here's a way using grep:

(IFS=$'\n' && echo "${MY_ARR[*]}") | grep '[^.]*.pattern/[^.]*.txt'

The meat here is that IFS=$'\n' causes "${MY_ARR[*]}" to expand with newlines separating the items, so it can be piped through grep.

In particular, this will handle spaces embedded inside the items of the array.

Related