问题描述
echoThere'是< strong> 54< / strong>城市| grep -o([0-9] +)
我想如何让它返回54?我试过上面的grep命令,它不起作用。
echo你有< strong> 54< / strong>| grep -o'[0-9]'
似乎有点工作,但它可以打印
5
4
而不是 54
您需要使用E在我的Mac OSX上:
$ echo有< strong> 54<< ; /强>城市| grep -Eo[0-9] +
54
您也需要考虑行中是否会出现一个以上的数字,应该是什么样的行为呢?
编辑1:由于您现在指定了要求是< strong>
标记之间的数字,我会推荐使用sed。在我的平台上,grep没有perl样式正规表达式的P选项。我的另一个盒子, grep
的版本指定这是一个实验性功能,所以我会在这种情况下使用 sed
。
$ echo有< strong> 54< / strong> 12个城市| sed -rn's /^.*& lt; strong> \\ * *([0-9] +)\s *< \ / strong>。* $ / \ 1 / p'
54
这里r
是扩展正则表达式。
编辑2:如果你在你的grep版本中有PCRE选项,你也可以利用下面的正向lookbeheads和lookaheads。
$ echo有< strong> 54< / strong> 12个城市| grep -o -P(?)\s *([0-9] +)\s *(?=< \ / strong>)
54
I am trying to use grep to just capture a number in a string but I am having difficulty.
echo "There are <strong>54</strong> cities | grep -o "([0-9]+)"
How am I suppose to just have it return "54"? I have tried the above grep command and it doesn't work.
echo "You have <strong>54</strong>" | grep -o '[0-9]'
seems to sort of work but it prints
5
4
instead of 54
You need to use the "E" option for extended regex support (or use egrep). On my Mac OSX:
$ echo "There are <strong>54</strong> cities" | grep -Eo "[0-9]+"
54
You also need to think if there are going to be more than one occurrence of numbers in the line. What should be the behavior then?
EDIT 1: since you have now specified the requirement to be a number between <strong>
tags, I would recommend using sed. On my platform, grep does not have the "P" option for perl style regexes. On my other box, the version of grep
specifies that this is an experimental feature so I would go with sed
in this case.
$ echo "There are <strong>54</strong> 12 cities" | sed -rn 's/^.*<strong>\s*([0-9]+)\s*<\/strong>.*$/\1/p'
54
Here "r"
is for extended regex.
EDIT 2: If you have the "PCRE" option in your version of grep, you could also utilize the following with positive lookbehinds and lookaheads.
$ echo "There are <strong>54 </strong> 12 cities" | grep -o -P "(?<=<strong>)\s*([0-9]+)\s*(?=<\/strong>)"
54
这篇关于Grep:捕获数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!