LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   extract last number from filename (https://www.linuxquestions.org/questions/linux-newbie-8/extract-last-number-from-filename-810434/)

csegau 05-27-2010 06:59 AM

extract last number from filename
 
Hi all,

I have to extract last number from filename.

ex- my file name is a10b8c1000

so i want to extract 1000 from it.

i tried using sed
sed 's/[a-z][0-9]*[a-z][0-9]*[a-z]//g' a10b8c1000

but sed looks for content inside file.

Please help me...

Thanks

grail 05-27-2010 07:15 AM

try echoing the file name into sed:
Code:

echo a10b8c1000 | sed <blah>

David the H. 05-27-2010 07:27 AM

Here's a way, using only bash. Put the filename into a variable, then use parameter substitution to extract the substring.
Code:

$ filename='a10b8c1000'
$ echo ${filename##*[^0-9]}
1000


vinaytp 05-27-2010 07:31 AM

Dear David,

Looks Great and it works !!

Code:

$ filename='a10b8c1000'
$ echo ${filename##*[^0-9]}
1000

What is the significance of ## here ? How does this work, Can you please explain, or any link that helps in understanding echo ${filename##*[^0-9]}.

syg00 05-27-2010 07:39 AM

Every so often I remember parameter substitution - but I always have to go look it up. It just ain't natural.
regex just "is" - egrep in this case for me.

catkin 05-27-2010 07:54 AM

Quote:

Originally Posted by vinaytp (Post 3982858)
Can you please explain, or any link that helps in understanding echo ${filename##*[^0-9]}.

Try the parameter substitution link in David the H's post.

David the H. 05-28-2010 05:09 AM

unlike syg00, I love parameter substitution. It's flexible and powerful and I don't find it difficult at all. You really only need to memorize a handful of patterns to get most of the benefit, and many of those are similar to ones you encounter elsewhere. It's also more efficient than calling on external tools like sed. Of course it can't tackle everything, but it's great for doing simple text manipulations.

And yes, I posted the link so you could learn more about it yourself. But to summarize the pattern I used, it says "remove from the beginning the longest string that matches 'anything + not a number'".

catkin 05-28-2010 07:18 AM

Quote:

Originally Posted by David the H. (Post 3983967)
unlike syg00, I love parameter substitution. It's flexible and powerful ...

... and it runs a lot faster than running an external command (which may, of course, not be significant).

MTK358 05-28-2010 07:24 AM

Couldn't resist:

Code:

sed -r 's#.*([0-9]*)$#\1#'


All times are GMT -5. The time now is 01:13 PM.