For a fixed prefix length I can do it like so:
[ a${filename:0:2} = a.# ] && echo temporary emacs file
How to do it for an arbitrary prefix?
Is there a cleaner way?
For a fixed prefix length I can do it like so:
[ a${filename:0:2} = a.# ] && echo temporary emacs file
How to do it for an arbitrary prefix?
Is there a cleaner way?
[[
's =
operator takes a pattern in the right operand.
var=123
[[ 1234 = $var* ]] && ...
Here the 'regex' version (2015, bash 3.x and newer) of Ignacio's answer, using operator =~
:
[[ "1234" =~ ^12 ]] && echo y
If you need a dynamic prefix from a variable:
var=12
[[ "1234" =~ ^$var ]] && echo y
When using complex regular expressions you can place them in a own variable:
var=12
var2=a
regex="^${var}.+${var2}.+$"
[[ "1234a567" =~ $regex ]] && echo y
See also the 'Conditional Constructs' section of the Bash man page on command [[
:
An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.