sed you can do:
...where you would replace the
[num] above with some number representing the desired occurrence.
If the numbered occurrence you specify does not exist, as is demonstrated in the following example,
sed will simply print nothing at all.
echo ,2,3 | sed '/\n/P;//d;s/[^,]*/\n&\n/4;D'
Above the first match for a sequence of zero-or-more not-comma chars are the zero chars occurring before the first comma. The second is
2 and the third is
3 - there is no fourth occurrence of that pattern and so the substitution is not successful.
Note also that not every
sed will support the
\n newline escape in the right-hand-substitution field and you may have to replace the
n characters in the escape string with literal newlines.
With your string it does:
str='> Leslie Cheung April 1 ? Elvis August 16 ? Leonard Nimoy February 27'
for o in 1 2 3
do printf %s\\n "$str" |
...which is just a little
for loop which runs
sed 3 times trying for all 3
[^?]* matches and prints...
:1:> Leslie Cheung April 1
:2: Elvis August 16
:3: Leonard Nimoy February 27
...or one for each value of
You can expand on that a little to skip over
[num] not-null occurrences like:
until [ "$((i+=1))" -gt 10 ] &&
printf %s\\n "$str"
do printf %s ":$i:$str?"; done |
:3:> Leslie Cheung April 1
Elvis August 16
Leonard Nimoy February 27
:10:> Leslie Cheung April 1
It can also be inclusive. For example:
printf %s\\n "$str?$str" |
...which prints each on a separate line every third not-null sequence of alphanumeric and
_ characters in a concatenation of two of your strings...