nulldozer February 2016

Sed: Why does [^\]] not seem to work?

I was trying to match/output all the text before the first ] appeared:

sed -i -r 's/^([^\]]*).*/\1/' "$FILE.tmp"

Which surprisingly does not work.

However, searching for the other bracket does work:

sed -i -r 's/^([^\[]*).*/\1/' "$FILE.tmp"

Is this a sed bug or am I doing it wrong?

I know I can work around this using .*? which is good enough but this issue had me stumped for long enough that I'd like to know if there is something I missed.

(According --version, I am using GNU sed 4.2.2.)

Answers


hek2mgl February 2016

It should be:

sed -r 's/^([^]]+).*/\1/'

Note that you don't need to quote the ] if it appears in a character group.


Sylvain Defresne February 2016

You don't need to quote the closing bracket ]. In fact your regular expression is parsed as [^\] followed by a stray ].

You want to use the following regular expression (note the lack of quoting with \):

sed -i -r 's/^([^]].*).*/\1/' "$FILE.tmp"

The second regular expression works by chance because [ has no special meaning in a [] expression but you'll find that it also match lines that start by a \.

In fact, when using ] in a [] group, it must be the first character, or the second if the first one is a ^.

Post Status

Asked in February 2016
Viewed 2,095 times
Voted 11
Answered 2 times

Search




Leave an answer