I writing my script and got stuck in this function. Can someone help me?
I need to extract out the numbers inside a string.
Ex:
INPUT -> OUTPUT
abcdef123 -> 123
abc123def -> 123
123abcdef -> 123
a123bc45d -> 123 45
abcdefghi -> -1
Thank you!
sed "s/[^0-9]//g;s/^$/-1/;" filename
one way
echo "salkf4243lsfk" | tr -d '[[:alpha:]]' #or [a-z]
or in bash
#s="slfk32432sdf"
#echo ${s//[a-zA-Z]/} # or [!0-9]
Thanks all!
It works.
But how can we separate each numbers?
Anyway it's fine to me!
sed "s/[^0-9]*\([0-9][0-9]*\)[^0-9]*/ \1 /g;s/^[^0-9][^0-9]*$/-1/" filename
awk '{ gsub(/[[:alpha:]]|[[:punct:]]/," ")}1' file
fayya
November 22, 2007, 12:48pm
7
Hi I have a similar problem, I would like to get a number that falls within a range from a string.
ex. input: "abcd 9034 efg 1234 hi"
output: 9034
I would only want to get the number range from 9000-9999
I've tried to use sed/grep to get what I want for hours but not able to do it, can anyone advice on this? Thanks a lot!!!
grep '^9[0-9][0-9][0-9]$' <(printf "%s\n" $s)
Or GNU grep:
grep -oE '\b9[0-9]{3}\b' <(printf "$s")
fayya
November 22, 2007, 2:10pm
9
I tried
grep '^9[0-9][0-9][0-9]$' <( printf "%s\n", "9012 abc" )
But it returns "Missing name for redirect."
fayya
November 22, 2007, 2:13pm
10
and doesn't grep only grep the whole line?
I didn't quote the variable in that example.
grep '^9[0-9][0-9][0-9]$' <( printf "%s\n", 9012 abc )
For older shells:
printf "%s\n", 9012 abc|grep '^9[0-9][0-9][0-9]$'
fayya
November 22, 2007, 2:59pm
12
Thanks radoulov!! Really appreciate your help! It worked great.
I always use echo, I just wonder why echo doesn't work like printf, I tried
echo "9012 abc"|grep '^9[0-9][0-9][0-9]$'
fayya:
Thanks radoulov!! Really appreciate your help! It worked great.
I always use echo, I just wonder why echo doesn't work like printf, I tried
echo "9012 abc"|grep '^9[0-9][0-9][0-9]$'
Because you need the newline between the words (\n).
You can do it with GNU grep:
zsh-4.3.4-dev-2% echo "9012 abc 99999"|grep -Eo '\b9[0-9][0-9][0-9]\b'
9012
zsh-4.3.4-dev-2% echo "9012 abc 99999"|grep -Eo '9[0-9][0-9][0-9]'
9012
9999