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

Categories

0 votes
1.3k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...