User12547645
User12547645

Reputation: 8447

Unable to match character groups with grep

I would like to match the regex \[[A-Z\s]*\]. It seems like grep is unable to interpret [A-Z\s] as any upper-case letter or space. \[.*\] works, but is not specific enough for me.

A quick look into grep --help reveals that there are multiple options for regex.

  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  -e, --regexp=PATTERN      use PATTERN for matching

I do not seem to get it to work with any of these options. What am I doing wrong?

Background: I would like to go through logging information. The logger sometimes outputs information with [INFO] or [WARN ] or similar.

Upvotes: 0

Views: 41

Answers (1)

DevSolar
DevSolar

Reputation: 70293

Perl compatible regular expressions...

grep -P "\[[A-Z\s]*\]"

...work for me. Input:

[INFO]
[WARN ]
[TEST2]

Output:

[INFO]
[WARN ]

If you don't have PCRE available on your system,

grep "\[[A-Z[:space:]]*\]"

will work out of grep's builtin basic syntax.

Upvotes: 1

Related Questions