Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

regex - bash grep text within squared brackets

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

e.g. in:

32432423 jkhkjh [234] hkjh32 2342342

I am searching 234.

usually that should find it

 [(.*?)]

but not with

|grep [(.*?)]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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]

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...