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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
(?<=\[) indicates that there should be a preceding
(?=\]) indicates that there should be a following
\], but not to include them in the match output.
$ cat a.txt test hello..[113a6d9e-7b06-42c6-a52b-7a4e4d2e216c]... this is te [113a6d9e-7b06-42c6-a52b-7a4e4d2e216c]. this is hello $ grep -oP '(?<=\[)[^\]]*' a.txt 113a6d9e-7b06-42c6-a52b-7a4e4d2e216c 113a6d9e-7b06-42c6-a52b-7a4e4d2e216c
The simplest way would be to let
tr delete them:
$ grep -oE "\[[0-9].+\]" logfile | tr -d '' 113a6d9e-7b06-42c6-a52b-7a4e4d2e216c 113a6d9e-7b06-42c6-a52b-7a4e4d2e216c
Notice that the
tr utility doesn't know about regular expressions or patterns in quite the same way as the shell does. In this case, the
 operand is just the two characters