Chandan
Chandan

Reputation: 1

Regular expression to capture both integer and float in bash

Can anyone help to capture the both int and float vaules using reg expression

I have below reg exp which will capture only int values but need to modify this for foot value also

'^[[:space:]]*([[:digit:]]+)[[:space:]]*([kmg])b?[[:space:]]*$'

This works if the value is eg 23 MB but failing for 23.789 MB.

'^[[:space:]]*([[:digit:].]+)[[:space:]]*([kmg])b?[[:space:]]*$'

Upvotes: 0

Views: 76

Answers (2)

user1934428
user1934428

Reputation: 22227

Assuming that the string containing your number is stored in variable vstring, the following should do:

if [[ $vstring =~  ([+-]?[[:digit:]]+([.][[:digit:]]+)?) ]]
then
  number=${BASH_REMATCH[1]}
else
  echo No number in $vstring 1>&2
fi

This also assumes that a floating point has not exponential part (since you didn't mention it in your question). It works with i.e.

vstring="23.789 MB"
vstring=-35
vstring=18.167
vstring="The number is 0.987"

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You can use

^[[:space:]]*([0-9]+([.][0-9]+)?)[[:space:]]*([kmgKMG][bB]?)[[:space:]]*$

Details:

  • ^ - start of string
  • [[:space:]]* - zero or more whitespaces
  • ([0-9]+([.][0-9]+)?) - Group 1: one or more digits and then an optional Group 2 matching a . and then one or more digits
  • [[:space:]]* - zero or more whitespaces
  • ([kmgKMG][bB]?) - Group 3: k, m, g, K, M or G and then an optional b or B
  • [[:space:]]* - zero or more whitespaces
  • $ - end of string.

See this regex demo.

Upvotes: 2

Related Questions