Given a filename in the form someletters_12345_moreleters.ext
, I want to extract the 5 digits and put them into a variable.
So to emphasize the point, I have a filename with x number of characters then a five digit sequence surrounded by a single underscore on either side then another set of x number of characters. I want to take the 5 digit number and put that into a variable.
I am very interested in the number of different ways that this can be accomplished.
Use cut:
More generic:
Here's a prefix-suffix solution (similar to the solutions given by JB and Darron) that matches the first block of digits and does not depend on the surrounding underscores:
Building on jor's answer (which doesn't work for me):
There's also the bash builtin 'expr' command:
A little late, but I just ran across this problem and found the following:
I used it to get millisecond resolution on an embedded system that does not have %N for date:
Following the requirements
I found some
grep
ways that may be useful:or better
And then with
-Po
syntax:Or if you want to make it fit exactly 5 characters:
Finally, to make it be stored in a variable it is just need to use the
var=$(command)
syntax.