开发者

how to match "numbers around a comma" with sed?

i want to match 12,345 in the following string: adf99fgl12,345qsdfm34

In general case, i have a number (a price) with a comma, in a string that contains numbers, letters, and other symbols, but no other commas. I want to tell sed to extract the price, that is to say, all number before and after the comma, and the comma.

The closest expre开发者_如何学Gossion i found was:

echo adf99fgl12,345qsdfm34 | sed "s/[^0-9]*\([0-9]+,[0-9]*\)[^0-9]*/\1/"

Thank you


How about using grep instead of sed?

echo adf99fgl12,345qsdfm34 | grep -Eo '[0-9]+,[0-9]*'


to find text you are usually better off using grep:

echo uaiuiae12,3456udeaitentu676 | grep -o -E '([[:digit:]]+,[[:digit:]]+)'
  • -E will switch on extended regular expressions
  • -o will only output the match itself


Bash 3.2+

$ var="adf99fgl12,345qsdfm34"
$ [[ $var =~ '(.[^0-9]*)([0-9]*,[0-9]*)(.[^[0-9]*)' ]]
$ echo ${BASH_REMATCH[2]}
12,345
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜