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?
We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.
To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.
To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.
Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk .
[[
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With