user368507
user368507

Reputation: 1438

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 expression i found was:

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

Thank you

Upvotes: 0

Views: 3049

Answers (3)

knittl
knittl

Reputation: 265221

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

Upvotes: 1

kennytm
kennytm

Reputation: 523294

How about using grep instead of sed?

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

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342363

Bash 3.2+

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

Upvotes: 0

Related Questions