Using match to find substrings in strings with only bash

后端 未结 4 2098
无人共我
无人共我 2020-12-14 00:42

Although I am almost sure this has been covered, I can\'t seem to find anything specific to this. As I continue my journey on learning bash I keep finding parts where I am b

4条回答
  •  感动是毒
    2020-12-14 01:02

    You can use the BASH_REMATCH variable in bash to get the matched string:

    $ Stext="Hallo World"
    $ [[ $Stext =~ ^.[a-z]* ]] && echo $BASH_REMATCH
    Hallo
    $ [[ $Stext =~ ^(.[a-z]*) ]] && echo ${BASH_REMATCH[1]}
    Hallo
    

    Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

提交回复
热议问题