Bash : extracting part of a string

后端 未结 4 1407
时光说笑
时光说笑 2020-12-14 06:05

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

4条回答
  •  一生所求
    2020-12-14 06:17

    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}'`
    

提交回复
热议问题