0

I have variable

test="PlayLists: 00001.mpls 01:32:39 [12 chapters] 00005.mpls 00:19:37 [4 chapters] 00003.mpls 00:08:56 [1 chapters] 00004.mpls 00:00:39 [1 chapters] 00006.mpls 00:00:29 [2 chapters] 00007.mpls 00:00:25 [2 chapters] 00000.mpls 00:00:23 [1 chapters]"

I tried with:

chapters=$([[ $test =~ ((([0-9]+) chapters)+) ]] && echo "${BASH_REMATCH[1]}")
echo $chapters

But it returns only 12 chatpters, I want to get

12 chapters
4 chapters
1 chapters
...
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • 1
    Does this answer your question? [Multiple matches in a string using regex in bash](https://stackoverflow.com/questions/11565489/multiple-matches-in-a-string-using-regex-in-bash) – SamBob Oct 05 '21 at 13:29
  • 2
    If you don't need a pure-bash solution I'd simply use `grep -Eo '[0-9]+ chapters'` ([try it here](https://ideone.com/SyXqia)). – Aaron Oct 05 '21 at 13:32
  • @Aaron it was example output, I edited post to add ... – Snake Eyes Oct 05 '21 at 13:33
  • @SnakeEyes yeah I saw that, thank you for updating your question. Are the grep solution or the linked Q/A satisfactory? – Aaron Oct 05 '21 at 13:35

2 Answers2

3

See the following example for a pure bash solution.

Example script:

# cat foo.sh
shopt -s extglob
var='[12 chapters][13 chapters][14 chapters]'
while [[ $var =~ ([0-9]+ chapters) ]]; do
    echo "${BASH_REMATCH[1]}"
    var=${var#*+([0-9]) chapters}
done

The result:

# bash foo.sh
12 chapters
13 chapters
14 chapters
pynexj
  • 19,215
  • 5
  • 38
  • 56
1

If you don't need a pure-bash solution, I would simply use the following grep invocation :

grep -Eo '[0-9]+ chapters'

The regex matches a number followed by "chapters", the -E flag enables Extended Regular Expressions so we don't need to use the anticated Basic Regular Expression regex flavour, and the -o flag makes grep output each match alone on a single line rather than full lines that contain at least one match.

You can try it here.

Aaron
  • 24,009
  • 2
  • 33
  • 57