Sed:为什么[^ \]]似乎不起作用? [英] Sed: Why does [^\]] not seem to work?

查看:61
本文介绍了Sed:为什么[^ \]]似乎不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第一个] 出现之前,我试图匹配/输出所有文本:

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

令人惊讶的是,这行不通.

但是,搜索其他括号确实可以:

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

这是sed错误还是我做错了?

我知道我可以使用.*?来解决此问题,这已经足够了,但是这个问题使我陷入了很长一段时间,以至于我想知道是否错过了某些事情.

(根据--version,我使用的是GNU sed 4.2.2.)

解决方案

您无需引用右括号] .实际上,您的正则表达式被解析为 [^ \] ,后跟一个杂散的] .

您要使用以下正则表达式(请注意缺少用 \ 引用):

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

第二个正则表达式是偶然出现的,因为 [ [] 表达式中没有特殊含义,但是您会发现它也匹配以<代码> \ .

实际上,在 [] 组中使用] 时,它必须是第一个字符,如果第一个是 ^ <,则必须是第二个字符/code>.

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

这篇关于Sed:为什么[^ \]]似乎不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆