coreutils: String expressions
16.4.1 String expressions
-------------------------
‘expr’ supports pattern matching and other string operators. These have
higher precedence than both the numeric and relational operators (in the
next sections).
‘STRING : REGEX’
Perform pattern matching. The arguments are converted to strings
and the second is considered to be a (basic, a la GNU ‘grep’)
regular expression, with a ‘^’ implicitly prepended. The first
argument is then matched against this regular expression.
If the match succeeds and REGEX uses ‘\(’ and ‘\)’, the ‘:’
expression returns the part of STRING that matched the
subexpression; otherwise, it returns the number of characters
matched.
If the match fails, the ‘:’ operator returns the null string if
‘\(’ and ‘\)’ are used in REGEX, otherwise 0.
Only the first ‘\( ... \)’ pair is relevant to the return value;
additional pairs are meaningful only for grouping the regular
expression operators.
In the regular expression, ‘\+’, ‘\?’, and ‘\|’ are operators which
respectively match one or more, zero or one, or separate
alternatives. SunOS and other ‘expr’’s treat these as regular
characters. (POSIX allows either behavior.) ⇒Regular
Expression Library (regex)Top, for details of regular expression
syntax. Some examples are in ⇒Examples of expr.
‘match STRING REGEX’
An alternative way to do pattern matching. This is the same as
‘STRING : REGEX’.
‘substr STRING POSITION LENGTH’
Returns the substring of STRING beginning at POSITION with length
at most LENGTH. If either POSITION or LENGTH is negative, zero, or
non-numeric, returns the null string.
‘index STRING CHARSET’
Returns the first position in STRING where the first character in
CHARSET was found. If no character in CHARSET is found in STRING,
return 0.
‘length STRING’
Returns the length of STRING.
‘+ TOKEN’
Interpret TOKEN as a string, even if it is a keyword like MATCH or
an operator like ‘/’. This makes it possible to test ‘expr length
+ "$x"’ or ‘expr + "$x" : '.*/\(.\)'’ and have it do the right
thing even if the value of $X happens to be (for example) ‘/’ or
‘index’. This operator is a GNU extension. Portable shell scripts
should use ‘" $token" : ' \(.*\)'’ instead of ‘+ "$token"’.
To make ‘expr’ interpret keywords as strings, you must use the
‘quote’ operator.