Atlas
Atlas

Reputation: 199

Regular expression does not match `]` symbol

My goal is to display only the text after last ] symbol.

echo MY_TEXT | grep -o "[^\]]*$"

The output is just the last symbol. If I change "]" symbol to any letter, it works as expected.

Examples:

$ echo Hello World | grep -o '[^o]*$'
rld  # and this is correct!
$ echo He]ll]o Wo]rld | grep -o "[^\]]*$"
d   # but expected: rld

Why behavior is different for symbol o and ]?

Thank you in advance.

Upvotes: 0

Views: 390

Answers (3)

Chris Seymour
Chris Seymour

Reputation: 85845

At couple of thing: [ doesn't need escaping inside a character class, you can use --color to see only the letters are match and notice -o splits each match on a new line:

$ echo "He]ll]o Wo]rld" | grep -o '[^]]*$'
rld

$ echo "He]ll]o Wo]rld" | grep --color '[^]]*'
He]ll]o Wo]rld

$ echo "He]ll]o Wo]rld" | grep -o '[^]]*'
He
ll
o Wo
rld

You can strip the ] character using tr among many other ways:

$ echo "He]ll]o Wo]rld" | tr -d ']'
Hello World

Upvotes: 1

perreal
perreal

Reputation: 98048

You do not need to escape the ]:

echo 'He]ll]o Wo]rld' | grep -o "[^]]*$"

Produces: rld

Upvotes: 3

alex
alex

Reputation: 490423

Removed the escape character and it worked for me.

$ echo He]ll]o Wo]rld | grep -o "[^]]*$"
> rld

Upvotes: 0

Related Questions