Just to make it clear, the named character class as enclosed by
[::] is equal to a predefined set of characters. This is separate from the
[] character range expression. You generally use the first one inside the second one.
So
[:digit:] is equal to
0-9, and
[[:digit:]] is equal to
[0-9].
http://mywiki.wooledge.org/RegularExpression
By the way, the use of
expr is generally unnecessary in most modern shells. Almost everything that it can do is now built-in in some form or other.
Here are a few ways to extract a string of digits using only shell built-ins (with a guess about your directory name format).
Code:
sdir='SA1234FOOBAR'
prepend="${sdir#SA}"
prepend="${prepend%%[^[:digit:]]*}"
echo "$prepend"
This uses standard parameter expansions supported by all posix shells (see link below).
In fact, if there's only a single string of digits in the name, you could even use this:
Code:
prepend="${sdir//[^[:digit:]]}"
If you have a fairly modern version of bash (v3+), you can also use this:
Code:
re='SA([[:digit:]]*)'
[[ $sdir =~ $re ]] && echo prepend="${BASH_REMATCH[1]}"
The
[[ test can be used to apply a regex to the string, with the matched substring and any captures being held in the
BASH_REMATCH array. Note that it's generally advisable to store the regex in a separate variable, to avoid having to backslash reserved characters on the right-hand-side of the expression (the regex as a whole needs to be unquoted in order to work).
They may take an extra line or two of code, but since everything is done internally, they should be more efficient than calling an external tool like
expr.
parameter expansion
string manipulation