Lazuardi N Putra
Lazuardi N Putra

Reputation: 428

regular expression to extract number from string

I want to extract number from string. This is the string

#all/30

All I want is 30. How can I extract? I try to use :

echo "#all/30" | sed 's/.*\/([^0-9])\..*//'

But nothing happen. How should I write for the regular expression? Sorry for bad english.

Upvotes: 0

Views: 283

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

echo "all/30" | sed 's/[^0-9]*//g'
# OR
echo "all/30" | sed 's#.*/##'
# OR
echo "all/30" | sed 's#.*\([0-9]*\)#\1#'

without more info about possible input string we can only assume that structure is #all/ followed by the number (only)

Upvotes: 0

Harshada
Harshada

Reputation: 1

echo "all/30" | sed 's/[^0-9]*\/\([0-9][0-9]*\)/\1/'

Avoid writing '.*' as it consumes entire string. Default matches are always greedy.

Upvotes: 0

hwnd
hwnd

Reputation: 70750

You may consider using grep to extract the numbers from a simple string like this.

echo "#all/30" | grep -o '[0-9]\+'
  • -o option shows only the matching part that matches the pattern.

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174844

You could try the below sed command,

$ echo "#all/30" | sed 's/[^0-9]*\([0-9]\+\)[^0-9]*/\1/'
30
  • [^0-9]* [^...] is a negated character class. It matches any character but not the one inside the negated character class. [^0-9]* matches zero or more non-digit characters.
  • \([0-9]\+\) Captures one or more digit characters.
  • [^0-9]* Matches zero or more non-digit characters.
  • Replacing the matched characters with the chars inside group 1 will give you the number 30

Upvotes: 1

Related Questions