Grep Command – How to Search Strings with Square Brackets

grepregular expression

This is the data

10:43:19.538281|TraceDetail    |UPBSStandardGenericBillPaymentComponent.PostBillPaymentTransaction|Total Time    19/06/2019 10:43:19.538281|TraceDetail    |UPBSStandardGenericBillInquiryComponent.GetBillInquiry()|Total Time                    |2361748             | Consumer Number [0312122221212             ] , UCID [KLOJ0001] ,  Sending Time [10:43:17.8425459] Receive Time [10:43:18.4941158] Total Time [0:0:651] STAN is [345949]

I want output

[0312122221212             ]
[KLOJ0001]
[10:43:17.8425459]
[10:43:18.4941158]
[0:0:651]
[345949]

I have tried so many commands but didn't able to achieve the result with following command:

grep -oP 'Consumer Number \K.{26}|UCID \K.{10} |Sending Time \K.{09}|Receive Time \K.{09}|Total Time \\[ \K.{8}|STAN is \K.{8}' /root/Documents/a.txt

I got output without total time:

[0312122221212             ]
[KLOJ0001]
[10:43:17.8425459]
[10:43:18.4941158]
[345949]

And when I try this command:

grep -oP 'Consumer Number \K.{26}|UCID \K.{10} |Sending Time \K.{09}|Receive Time \K.{09}|Total Time \K.{8}|STAN is \K.{8}' /root/Documents/a.txt

I got invalid values in output:

19/06/
[0312122221212             ]
[KLOJ0001]
[10:43:17.8425459]
[10:43:18.4941158]
[0:0:651]
[345949]

Best Answer

You can use simply this:

grep -oP '\[.*?\]' /root/Documents/a.txt

\[ matches a literal [

.*? matches any number of chars, in a non-greddy (lazy) way.

> Laziness Instead of Greediness

\] matches a literal ]


Now, I'll try to explain what went wrong with your regexes.

this one:

grep -oP 'Consumer Number \K.{26}|UCID \K.{10} |Sending Time \K.{09}|Receive Time \K.{09}|Total Time \\[ \K.{8}|STAN is \K.{8}' /root/Documents/a.txt

is broken: grep: missing terminating ] for character class you probably paste it badly here... check that out.

And this one:

grep -oP 'Consumer Number \K.{26}|UCID \K.{10} |Sending Time \K.{09}|Receive Time \K.{09}|Total Time \K.{8}|STAN is \K.{8}' /root/Documents/a.txt

Could be fixed:

grep -oP 'Consumer Number \K.{29}|UCID \K.{10} |Sending Time \K.{09}|Receive Time \K.{09}|Total Time \K[^/ ]{9}|STAN is \K.{8}' /root/Documents/a.txt

but bare in mind that this in not the best way to do it... the problem with your original regex was that you were too permissive; so, you were matching things you don't intended; if you know that some match should only contain, say, [,numbers, space, and ], don't use .{29}... this is SO permissive with no point: be more precise, for example, like this: [][0-9 ]{29}

Related Question