Nathan Cheval
Nathan Cheval

Reputation: 843

Get multiple values between brackets

I want to retrieve multiple strings between brackets. Here is the command I use for now:

grep '\[*\]' src/config/mail.ini

It returns me output like:

[GLOBAL]
[MAIL_1]

How could I get the result one by one? And, in this case, as two variables?

Upvotes: 2

Views: 285

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You may use

grep -o '\[[^][]*]' src/config/mail.ini

See the online grep demo

The -o option makes grep extract the matched substrings instead of printing matching lines, and the \[[^][]*] pattern matches:

  • \[ - a [ char
  • [^][]* - 0 or more chars other than ] and [ ("smart placement" is used, the ] at the start of the bracket expression is treated as ] and the [ char is not special inside a bracket expression)
  • ] - a ] char (no need to escape ]).

To process match by match:

while read -r line ; do
    echo "Processing $line"
    # your code goes here
done < <(grep -o '\[[^][]*]' src/config/mail.ini)

Upvotes: 3

Related Questions