0

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.

4 Answers 4

4

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.
Sign up to request clarification or add additional context in comments.

1 Comment

@AvinashRaj Both of answer give me what I need sir. I just need 30 for output.
1

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

1 Comment

Finally, it works. I never thought it should be a long-code-regex. By the way, thank you very much Sir.
0
echo "all/30" | sed 's/[^0-9]*\/\([0-9][0-9]*\)/\1/'

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

1 Comment

echo "all/30" | sed 's#[^0-9]*/\([0-9]\{1,\}\)#\1#'
0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.