说我有字符串"Memory Used:19.54M"我如何从中提取19.54?19.54将经常更改,因此我需要将其存储在变量中并将其与下一次迭代的值进行比较.
我想我需要一些grep和regex的组合,但我从来没有真正理解正则表达式..
cho*_*oba 74
您可能想要提取它而不是删除它.您可以使用参数扩展来提取值:
var="Memory Used: 19.54M"
var=${var#*: } # Remove everything up to a colon and space
var=${var%M} # Remove the M at the end
Run Code Online (Sandbox Code Playgroud)
注意bash只能比较整数,它没有浮点算术支持.
Oni*_*iel 40
其他可能的方案:
用grep:
var="Memory Used: 19.54M"
var=`echo "$var" | grep -o "[0-9.]\+"`
Run Code Online (Sandbox Code Playgroud)
用sed:
var="Memory Used: 19.54M"
var=`echo "$var" | sed 's/.*\ \([0-9\.]\+\).*/\1/g'`
Run Code Online (Sandbox Code Playgroud)
用cut:
var="Memory Used: 19.54M"
var=`echo "$var" | cut -d ' ' -f 3 | cut -d 'M' -f 1`
Run Code Online (Sandbox Code Playgroud)
用awk:
var="Memory Used: 19.54M"
var=`echo "$var" | awk -F'[M ]' '{print $4}'`
Run Code Online (Sandbox Code Playgroud)