'sed output first match only between brackets

using sed, i would like to extract the first match between square brackets. i couldn't come up with a matching regex, since it seems that sed is greedy in its regex. for instance, given the regex \[.*\] - sed will match everything between the first opening bracket and the last closing bracket, which is not what i am after (would appreciate your help on this).

but until i could come up with a regex for that, i made an assumption that there must be a space after the closing bracket, to come up with a regex that will let me continue my work \[[^ ]*\].

i have tried it with grep, e.g.

$ echo '++  *+   ++ + [SPAM] foo(): z.y.o ## [x.y.z]----- ' | grep -oE '\[[^ ]*\]'
[SPAM]
[x.y.z]

i would like to use the regex in sed (not in grep) and output the first match (i.e. [SPAM]). i have tried it as follows, but wasn't able to do that

$ echo '++  *+   ++ + [SPAM] foo(): z.y.o ## [x.y.z]----- ' | sed 's/\[[^ ]*\]/\1/'
sed: 1: "s/\[[^ ]*\]/\1/": \1 not defined in the RE

$ echo '++  *+   ++ + [SPAM] foo(): z.y.o ## [x.y.z]----- ' | sed 's/\(\[[^ ]*\]\)/\1/'
++  *+   ++ + [SPAM] foo(): z.y.o ## [x.y.z]-----

would appreciate if you could assist me in:

  1. constructing a regex to match all text between every opening and closing square brackets (see grep example above)
  2. use the regex in sed and output only the first occurrence of the match
sed


Solution 1:[1]

You can use

grep -o '\[[^][]*]' <<< "$text"
sed -n 's/^[^[]*\(\[[^][]*]\).*/\1/p' <<< "$text"

See the online demo. Details:

  • grep -o '\[[^][]*]' - outputs only matching substrings that meet the pattern: [, then zero or more chars other than [ and ], and then a ] char
  • sed -n 's/^[^[]*\(\[[^][]*]\).*/\1/p':
    • -n - suppresses default line output
    • ^[^[]*\(\[[^][]*]\).* - matches start of string, then zero or more chars other than [, then captures into Group 1 a [, then any zero or more chars other than [ and ] and then a ] char, and then matches the rest of the string
    • \1 - replaces the match with Group 1 value
    • p - prints the result of the replacement.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew