Hide part of match from grep output

grepregular expression

I have a regex for session ID extraction:

[root@docker tmp]# grep -oE "\[[0-9].+\]" logfile
[113a6d9e-7b06-42c6-a52b-7a4e4d2e216c]
[113a6d9e-7b06-42c6-a52b-7a4e4d2e216c]
[root@docker tmp]#

How can I hide the square brackets from the output?

Best Answer

Instead of using extended-regex grep (-E), use perl-regex grep instead (-P), with a lookbehind and lookahead.

$ grep -oP "(?<=\[)[0-9].+(?=\])" logfile
113a6d9e-7b06-42c6-a52b-7a4e4d2e216c
113a6d9e-7b06-42c6-a52b-7a4e4d2e216c

Here, (?<=\[) indicates that there should be a preceding \[, and (?=\]) indicates that there should be a following \], but not to include them in the match output.

Related Question