Bash:提取字符串的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12671406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:46:20  来源:igfitidea点击:

Bash : extracting part of a string

bash

提问by confusified

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.

假设我有字符串 "Memory Used: 19.54M" 我如何从中提取 19.54?19.54 会经常变化,所以我需要将它存储在一个变量中,并将它与下一次迭代的值进行比较。

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

我想我需要 grep 和 regex 的某种组合,但我从来没有真正理解 regex ..

回答by choroba

You probably want to extractit rather than removeit. 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.

请注意,bash 只能比较整数,它没有浮点算术支持。

回答by Onilton Maciel

Other possible solutions:

其他可能的解决方案:

With grep:

grep

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

With sed:

sed

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

With cut:

cut

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

With awk:

awk

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

回答by Alastair

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

您可以将 bash regex 支持与=~运算符一起使用,如下所示:

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

This will print 19.54

这将打印 19.54

回答by Vijay

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