You could use expr
with regular expressions like this:
$ str='FRUIT=apple'
$ key=$(expr "$str" : '\([^=]*\)')
$ value=$(expr "$str" : '.*=\([^=]*\)')
$ echo "<$key> <$value>"
<FRUIT> <apple>
The expression expr string : regex
returns the number of characters matched, or (as used above) if there is a capture group \(...\)
, it'll return that capture group. The regex starts with an implicit ^
anchor.
The expression for key
matches everything up to the first =
sign; the one for value
captures everything after the (last) =
sign.
All this being said, expr
is a holdover from when shells weren't powerful enough to do text processing using built-ins; any modern shell can do it. For example:
Splitting on =
and reading into two variables:
IFS='=' read -r key value <<< "$str"
Using parameter expansion:
key=${str%=*}
value=${str#*=}