问题
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.)
回答1:
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 ^.
回答2:
It should be:
sed -r 's/^([^]]+).*/\1/'
Note that you don't need to quote the ] if it appears in a character group.
来源:https://stackoverflow.com/questions/35275040/sed-why-does-not-seem-to-work