bash 从字符串中提取可变长度的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16015590/
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
Extract number of variable length from string
提问by user937284
I want to extract a number of variable length from a string.
我想从字符串中提取一些可变长度。
The string looks like this:
该字符串如下所示:
used_memory:1775220696
I would like to have the 1775220696part in a variable. There are a lot of questions about this, but I could not find a solution that suits my needs.
我想把这个1775220696部分放在一个变量中。关于这个有很多问题,但我找不到适合我需求的解决方案。
回答by fedorqui 'SO stop harming'
You can use cut:
您可以使用cut:
my_val=$(echo "used_memory:1775220696" | cut -d':' -f2)
Or also awk:
或者也awk:
my_val=$(echo "used_memory:1775220696" | awk -F':' '{print }')
回答by choroba
Use parameter expansion:
使用参数扩展:
string=used_memory:1775220696
num=${string#*:} # Delete everything up to the first colon.
回答by Reddy SK
I used to use egrep
我以前用过 egrep
echo used_memory:1775220696 | egrep -o [0-9]+
Output:
输出:
1775220696
回答by Vijay
use the regex:
使用正则表达式:
s/^[^:]*://g
you use it with sed or perl and get the part you needed.
您将它与 sed 或 perl 一起使用并获得所需的部分。
> echo "used_memory:1775220696" | perl -pe 's/^[^:]*://g'
1775220696
回答by chepner
bashsupports regular-expression matching, but for a simple case like this it is overkill; use parameter expansion (see choroba's answer).
bash支持正则表达式匹配,但对于像这样的简单情况,它是矫枉过正的;使用参数扩展(参见choroba 的回答)。
For the sake of completeness, here's an example using regular expression matching:
为了完整起见,这里有一个使用正则表达式匹配的示例:
[[ $string =~ (.*):([[:digit:]]+) ]] && num=${BASH_REMATCH[2]}
回答by A human being
Can be done using awk, like this:
可以使用 awk 完成,如下所示:
var=`echo "used_memory:1775220696" | awk -F':' '{print ;}'`
echo $var
output:
输出:
1775220696
回答by Benjamin W.
If your number could be anywhere in the string, but you know that the digits are contiguous, you can use shell parameter expansion to remove everything that is not a digit:
如果您的数字可以在字符串中的任何位置,但您知道数字是连续的,则可以使用 shell 参数扩展来删除所有不是数字的内容:
$ str=used_memory:1775220696
$ num=${str//[!0-9]}
$ echo "$num"
1775220696
This works also for used_memory:1775220696andmoretextand 123numberfirst. However, something like abc123def456would become 123456.
这也适用于used_memory:1775220696andmoretext和123numberfirst。但是,类似的东西abc123def456会变成123456.

