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

泪湿孤枕 提交于 2020-06-15 18:46:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!