46

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?

1

2 Answers 2

61

[['s = operator takes a pattern in the right operand.

var=123
[[ 1234 = $var* ]] && ...
Sign up to request clarification or add additional context in comments.

3 Comments

Do you mean [[ ${var_to_test}a = ${prefix}*a ]] && ...?
You don't need the a at the end; [[ does not have the same limitations as test.
You're right. If there is a variable on the left hand side even if it empty the expression still works (I was confused due to I've tested it in the shell without any name on the lhs, so it'd produced syntax errors; but in a script there always will be some variable name.)
31

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.