45

Say I have the string "Memory Used: 19.54M" How would I extract the 19.54 from it? The 19.54 will change frequently so i need to store it in a variable and compare it with the value on the next iteration.

I imagine I need some combination of grep and regex, but I never really understood regex..

1

4 Answers 4

88

You probably want to extract it rather than remove it. You can use the Parameter Expansion to extract the value:

var="Memory Used: 19.54M"
var=${var#*: }            # Remove everything up to a colon and space
var=${var%M}              # Remove the M at the end

Note that bash can only compare integers, it has no floating point arithmetics support.

Sign up to request clarification or add additional context in comments.

5 Comments

Extract does better explain what I want to do. How then would I change the third line to remove the "." and all that follows it?
${var%.*} removes a dot and anything following it at the end of the string.
may i ask what does # and * here means?
@once: As written in the comments, # means "remove from the left", and * is just a wildcard that matches everything.
Same effect could be archived with ${var//[A-Z,a-z,:]}
52

Other possible solutions:

With grep:

var="Memory Used: 19.54M"
var=`echo "$var" | grep -o "[0-9.]\+"`

With sed:

var="Memory Used: 19.54M"
var=`echo "$var" | sed 's/.*\ \([0-9\.]\+\).*/\1/g'`

With cut:

var="Memory Used: 19.54M"
var=`echo "$var" | cut -d ' ' -f 3 | cut -d 'M' -f 1`

With awk:

var="Memory Used: 19.54M"
var=`echo "$var" | awk -F'[M ]' '{print $4}'`

Comments

4

You can use bash regex support with the =~ operator, as follows:

var="Memory Used: 19.54M"
if [[ $var =~ Memory\ Used:\ (.+)M ]]; then
    echo ${BASH_REMATCH[1]}
fi

This will print 19.54

Comments

1
> echo "Memory Used: 19.54M" | perl -pe 's/\d+\.\d+//g'
Memory Used: M

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.