Skip to main content
5 of 9
edited body
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k

I'm assuming that you are using the bash shell. Do consider tagging your question with the appropriate shell that you are using.

Using readarray in the bash shell, and GNU sed:

readarray -t my_array < <( my_command | sed -n '2~2p' )

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~2d').

In GNU sed, the address n~m addresses every m:th line starting at line n. This is a GNU extension to standard sed.

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
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k