Bash : extracting part of a string

后端 未结 4 1405
时光说笑
时光说笑 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}'`
    
    0 讨论(0)
  • 2020-12-14 06:21
    > echo "Memory Used: 19.54M" | perl -pe 's/\d+\.\d+//g'
    Memory Used: M
    
    0 讨论(0)
  • 2020-12-14 06:22

    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.

    0 讨论(0)
  • 2020-12-14 06:24

    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

    0 讨论(0)
提交回复
热议问题