Using readarray
in the bash
shell, and GNU sed
:
readarray -t my_array < <( my_command | sed -n '2~2p''1~2d' )
The built-in readarray
reads the lines into an array. The lines are read from a process substitution. The sed
command in the process substitution will only output every second line read from my_command
(and could also be written sed '1!n;d'
, or as sed -n 'n;p'
with standard sed
).
In GNU sed
, the address n~m
addresses every m
:th line starting at line n
. This is a GNU extension to standard sed
, for convenience.
The my_command
command will only ever be called once.
Testing:
$ readarray -t my_array < <( seq 10 | sed '1~2d' )
$ printf '%s\n' "${my_array[@]}"
2
4
6
8
10