bash grep文本放在方括号内 [英] bash grep text within squared brackets

查看:188
本文介绍了bash grep文本放在方括号内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从linux bash上的日志文件中提取文本.文本在两个方括号内.

I try to grep a text from a log file on a linux bash.The text is within two square brackets.

例如在:

32432423 jkhkjh [234] hkjh32 2342342

我正在搜索234.

通常应该找到它

 \[(.*?)\]

但不

|grep \[(.*?)\]

使用grep进行正则表达式搜索的正确方法是什么

what is the correct way to do the regular expression search with grep

推荐答案

您可以查找左括号,并使用\K转义符清除.然后,匹配右括号:

You can look for an opening bracket and clear with the \K escape sequence. Then, match up to the closing bracket:

$ grep -Po '\[\K[^]]*' <<< "32432423 jkhkjh [234] hkjh32 2342342"
234

请注意,您可以这样说来忽略-P(Perl扩展的正则表达式):

Note you can omit the -P (Perl extended regexp) by saying:

$ grep -o '\[.*]' <<< "32432423 jkhkjh [234] hkjh32 2342342"
[234]

但是,如您所见,这也会打印括号.这就是为什么让-P进行回溯和回溯的原因很有用.

However, as you see, this prints the brackets also. That's why it is useful to have -P to perform a look-behind and look-after.

您还需要在正则表达式中提及?.好吧,正如您已经知道的那样,*?是要使正则表达式匹配以非贪婪的方式表现.让我们看一个例子:

You also mention ? in your regexp. Well, as you already know, *? is to have a regex match behave in a non-greedy way. Let's see an example:

$ grep -Po '\[.*?]' <<< "32432423 jkhkjh [23]4] hkjh32 2342342"
[23]
$ grep -Po '\[.*]' <<< "32432423 jkhkjh [23]4] hkjh32 2342342"
[23]4]

对于.*?,在[23]4]中与[23]匹配.仅使用.*,它与最后一个]匹配,因此得到[23]4].此行为仅与-P选项一起使用.

With .*?, in [23]4] it matches [23]. With just .*, it matches up to the last ] hence getting [23]4]. This behaviour just works with the -P option.

这篇关于bash grep文本放在方括号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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