Bash string extraction / manipulation

I have a complex string form

"xxxp + NUMyyy"

where xxx, NUM and yyy are variable length, and '+' can be a mathematical operator, such as '-', '*', '/' or '='.

I am trying to find the best way to get which math operator and number the user entered.

I tried using a combination of these things:

echo `expr match "tcp+111" '\([+-=*/]\)'` echo `expr match "tcp+111" '\(\+\-=\*/\)'` 

Nothing has been done yet. I think the easiest way to do this is to use regular expressions, but maybe I'm wrong? What is a good way to do this?

Thanks.

Example input: "tcjp-100" "p + 1" "p + 1: debug" "cp = 11: v". I forgot to mention, the operator will always have the letter "p". In addition, "xxx" and "yyy" should not be present, but may be

+4
source share
1 answer

You can use the bash regex matching function.

 string="xxxp+3456yyy" pattern="[^*/+-]*([*/+-]*)([[:digit:]]+).*" # the hyphen must come last (or first, but after ^) in the character sets [[ $string =~ $pattern ]] echo "${BASH_REMATCH[1]}" # operator echo "${BASH_REMATCH[2]}" # number 
+4
source

All Articles