Det
Det

Reputation: 3710

Bash array: remove elements starting with dash (-)

Say I have the following array, where the elements may be ordered in any way:

items=('this-item' 'that-item' '-fd')

How do I remove the one starting with dash (-fd)?

Upvotes: 0

Views: 212

Answers (1)

konsolebox
konsolebox

Reputation: 75488

This is one way:

for i in "${!items[@]}"; do
    [[ ${items[i]} == -* ]] && unset "items[$i]"  ## Or unset 'items[i]'
done

# Optionally re-align indices:
items=("${items[@]}")

If you just want to remove the third element anyway you can just have:

items=("${items[@]:0:2}")

Or just

unset 'items[2]'

If you have more than 3 elements:

items=(1 2 3 4 5)
items=("${items[@]:0:2}" "${items[@]:3}")

Or just

unset 'items[2]'; items=("${items[@]}")

Note that array indices start at 0. It may also be different if some indices were deleted.

Upvotes: 3

Related Questions