w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to capture all substrings in bash

Sure. You can build the regular expression dynamically (you just remember the result of the longest matching regex):

#! /bin/bash
temp_input='[a1b] hjh [d;] , [45]'

regex='[(.*)]'
for (( i=0 ; i<${#temp_input}/2 ; i++ )) ; do
    regex+='.*[(.*)]'
    if [[ $temp_input =~ $regex ]] ; then
        matches=("${BASH_REMATCH[@]}")
    fi
done

for (( m=1; m<${#matches[@]} ; m++ )) ; do
    echo "${matches[m]}"
done

Here is how you can do it without the =~ operator, iterating over the input character by character:

#! /bin/bash
temp_input='[a1b] hjh [d;] , [45]'

matches=()
string=''
in=0

for ((i=0 ; i<${#temp_input} ; i++)) ; do
    char=${temp_input:i:1}
    if ((in)) ; then
        if [[ $char == ] ]] ; then
            in=0
            matches+=("$string")
            string=''
        else
            string+=$char
        fi
    fi
    if [[ $char == [ ]] ; then
        in=1
    fi
done

for m in "${matches[@]}" ; do
    echo "$m"
done

Or shorter, using a different type of parameter expansion + pattern matching:

#! /bin/bash
temp_input='[a1b] hjh [d;] , [45]'

matches=()
while [[ $temp_input == *[*]* ]] ; do
    temp_input=${temp_input#*[}
    t=${temp_input%%]*}
    matches+=("$t")
done

for m in "${matches[@]}" ; do
    echo "$m"
done




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.