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

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

问题描述

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

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天全站免登陆