Using match to find substrings in strings with only bash

后端 未结 4 2092
无人共我
无人共我 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 00:52

    I made this simple function:

    match() {
        TRUE=1
        FALSE=0
        match_return=0
        echo $1 | grep $2 >/dev/null
        [ $? -eq 0 ] && match_return=$TRUE || match_return=$FALSE
    }
    

    Usage:

    match Testing Test ; [ $match_return -eq 1 ] && echo "match!" || echo "nope"
    

    entire code: https://gist.github.com/TeeBSD/5121b3711fad40a09455

    0 讨论(0)
  • 2020-12-14 00:58

    For quick string searches ... One option is grep.
    If not found, returns empty, else it is a match:

    found=`echo $big | grep -e $short`
    
    if [ ! -z $found ]; then echo 'There is a match'; else echo 'No no'; fi
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 01:07

    Both expressions are equivalent, the difference is the regular expression you use:

    $ echo `expr "$Stext" : '^\(.[a-z]*\)'`
    Hallo
    $ echo `expr "$Stext" : '^.[a-z]*'`
    5
    $ echo `expr "$Stext" : '\(.*World\)'`
    Hallo World
    $ echo `expr "$Stext" : '.*World'`
    11
    

    As you can see, parentheses is what makes the difference to either return the length of the match or the match itself.

    You can find more examples in Chapter 10 of the Advanced Bash-Scripting Guide.

    0 讨论(0)
提交回复
热议问题