Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash grep text within squared brackets

Tags:

regex

grep

bash

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

like image 878
user3732793 Avatar asked Aug 27 '26 20:08

user3732793


1 Answers

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.

like image 171
fedorqui 'SO stop harming' Avatar answered Aug 30 '26 10:08

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!