Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Extract numbers from String

Tags:

bash

shell

unix

I got a string which looks like this:

"abcderwer 123123 10,200 asdfasdf iopjjop"

Now I want to extract numbers, following the scheme xx,xxx where x is a number between 0-9. E.g. 10,200. Has to be five digit, and has to contain ",".

How can I do that?

Thank you

like image 310
user1360250 Avatar asked May 14 '12 08:05

user1360250


People also ask

How extract only numbers from string in shell script?

Replaces all non numbers with spaces: sed -e 's/[^0-9]/ /g' Remove leading white space: -e 's/^ *//g' Remove trailing white space: -e 's/ *$//g' Squeeze spaces in sequence to 1 space: tr -s ' '

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.


4 Answers

You can use grep:

$ echo "abcderwer 123123 10,200 asdfasdf iopjjop" | egrep -o '[0-9]{2},[0-9]{3}'
10,200
like image 91
codaddict Avatar answered Nov 15 '22 06:11

codaddict


In pure Bash:

pattern='([[:digit:]]{2},[[:digit:]]{3})'
[[ $string =~ $pattern ]]
echo "${BASH_REMATCH[1]}"
like image 32
Dennis Williamson Avatar answered Nov 15 '22 08:11

Dennis Williamson


Simple pattern matching (glob patterns) is built into the shell. Assuming you have the strings in $* (that is, they are command-line arguments to your script, or you have used set on a string you have obtained otherwise), try this:

for token; do
  case $token in
    [0-9][0-9],[0-9][0-9][0-9] ) echo "$token" ;;
  esac
done
like image 24
tripleee Avatar answered Nov 15 '22 06:11

tripleee


Check out pattern matching and regular expressions.

Links:

Bash regular expressions

Patterns and pattern matching

SO question

and as mentioned above, one way to utilize pattern matching is with grep. Other uses: echo supports patterns (globbing) and find supports regular expressions.

like image 21
keyser Avatar answered Nov 15 '22 06:11

keyser