Home > Software design >  Multiple regex matches in one string in bash
Multiple regex matches in one string in bash

Time:10-06

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
...

CodePudding user response:

See the following example for a pure bash solution.

The 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

CodePudding user response:

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.

  •  Tags:  
  • bash
  • Related