In a bash script, I would like to extract sub-string of the form key=[value], so that I can get the value in a variable by specifying the correspondingkey.
For instance, given this variable txt:
txt="something... key=[value] number=[0.42] ...other things... text=[foo] etc"
I would like to extract value for key, 0.42 for number, foo for text ... and empty string for missing keys.
I tried this command, to extract value:
echo "$txt" | sed 's/^*key=\[[*]\]*/\1/'
If I understood well, the command sed "s/regexp/replacement/" try to match here the following regexp:
^ the beginning of the line
* anything
key=\[ the beginning of what I want to find
[*^\[] match anything, except character [
\] the end of what I want to find
* anything
$ the end of the line
and replace it with what has been matched (due to \1).
But I am missing something since I get the following error message : sed: -e expression #1, char 27: invalid reference \1 on `s' command's RHS
I also tried this, without using \1:
echo "$txt" | sed 's/^*key=\[[*]\]*/TEST/'
But the regex failed to match and all the string of txt is returned...
globsandregexes. With a glob,*meansany character, any time. With regexes, it is only a quantifier (any amount of time), but you still have to specify which pattern is repeated. The equivalent in regex is.*. This website is a good tool to test your regexes.