[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: removing null elements from an array
From: |
Stephane Chazelas |
Subject: |
Re: removing null elements from an array |
Date: |
Fri, 18 Jul 2008 12:56:13 +0100 |
User-agent: |
Mutt/1.5.16 (2007-09-19) |
On Thu, Jul 17, 2008 at 11:12:47PM +0000, Poor Yorick wrote:
> To get rid of null elements in an array, I currently do something like this:
>
> bash-3.2$ var1=("with spaces" "more spaces" '' "the end")
> bash-3.2$ for v in "${var1[@]}"; do if test "$v"; then var2+=("$v"); fi;
> done
> bash-3.2$ echo ${#var2[@]}
> 3
> bash-3.2$ printf '%s\n' "${var2[@]}"
> with spaces
> more spaces
> the end
[...]
A note though: bash arrays are more associative arrays (with
keys limited to positive integers) more than arrays.
If you have a bash array with:
12 => ""
123 => foo
3456 => bar
Your method will turn it into:
0 => foo
1 => bar
With recent versions of bash, you could do:
for i in "${!var1[@]}"; do
[ -n "${var1[$i]}" ] || unset "var1[$i]"
done
For comparison,
In zsh, arrays are arrays, and there is a difference variable
type for associative arrays (whose keys are not limited to
integers).
In zsh, removing the empty elements is just a matter of
var1=($var1)
because $var1 expands to the list of non-empty elements in the
array by default (you need "$var1[@]" to include the empty
ones).
In zsh,
a[3]=foo
on an empty array is the same as
a=("" "" foo)
And with an associative array such as:
typeset -A h
h[foo]=bar
h[empty]=""
To remove the empty ones:
h=("${(kv@)h[(R)?*]}")
for instance.
--
Stéphane