Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash : extracting part of a string

Tags:

bash

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..

like image 457
confusified Avatar asked Oct 01 '12 10:10

confusified


1 Answers

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.

like image 68
choroba Avatar answered Sep 21 '22 17:09

choroba