How to extract numbers from a string?

前端 未结 10 1946
青春惊慌失措
青春惊慌失措 2020-12-10 04:20

I have string contains a path

string=\"toto.titi.12.tata.2.abc.def\"

I want to extract only the numbers from this string.

To extrac

10条回答
  •  有刺的猬
    2020-12-10 05:09

    Use regular expression matching:

    string="toto.titi.12.tata.2.abc.def"
    [[ $string =~ toto\.titi\.([0-9]+)\.tata\.([0-9]+)\. ]]
    # BASH_REMATCH[0] would be "toto.titi.12.tata.2.", the entire match
    # Successive elements of the array correspond to the parenthesized
    # subexpressions, in left-to-right order. (If there are nested parentheses,
    # they are numbered in depth-first order.)
    first_number=${BASH_REMATCH[1]}
    second_number=${BASH_REMATCH[2]}
    

提交回复
热议问题