简体   繁体   中英

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.)

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 ^ .

It should be:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM