How to extract numbers from a string?

前端 未结 10 2077
青春惊慌失措
青春惊慌失措 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

    Parameter expansion would seem to be the order of the day.

    $ string="toto.titi.12.tata.2.abc.def"
    $ read num1 num2 <<<${string//[^0-9]/ }
    $ echo "$num1 / $num2"
    12 / 2
    

    This of course depends on the format of $string. But at least for the example you've provided, it seems to work.

    This may be superior to anubhava's awk solution which requires a subshell. I also like chepner's solution, but regular expressions are "heavier" than parameter expansion (though obviously way more precise). (Note that in the expression above, [^0-9] may look like a regex atom, but it is not.)

    You can read about this form or Parameter Expansion in the bash man page. Note that ${string//this/that} (as well as the <<<) is a bashism, and is not compatible with traditional Bourne or posix shells.

提交回复
热议问题