1

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...

2
  • 1
    You are mixing up globs and regexes. With a glob, * means any 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. Commented May 24, 2018 at 11:47
  • Also, there are lots of other basic errors in your regex. Consider trying the website I linked in my previous comment to learn the regex syntax. Commented May 24, 2018 at 11:53

1 Answer 1

1

* doesn't match any string. * is a quantifier which says "the previous could be repeated zero or more times". You need a regex for sed, not a wildcard pattern:

sed 's/.*key=\[\([^]]*\)\].*/\1/'
  • \(...\) are needed to create a capture group, referenced as \1 (because it's the first such group)
  • [^]]* means "anything but ] zero or more times", so it matches the string inside square brackets
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.