7

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?

Sparhawk
20.5k20 gold badges97 silver badges160 bronze badges
asked Feb 28, 2017 at 9:27
5
  • can you post the contents of your logfile. may be you need awk command to process and get the desired output Commented Feb 28, 2017 at 9:32
  • @Kamaraj , Thank you for responding. awk is in my mind. But I am trying to solve this with only grep+regex. Commented Feb 28, 2017 at 9:33
  • can you post the contents of log file.. atleast 2 lines Commented Feb 28, 2017 at 9:34
  • 1
    Second you can pipe output trough | tr -d '][' e.g. Commented Feb 28, 2017 at 9:35
  • maybe this will work : grep -oE "[[0-9].+]" logifle | awk -F"[][]" '{print 2ドル}' Commented Feb 28, 2017 at 9:36

5 Answers 5

9

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.

answered Feb 28, 2017 at 9:37
0
2
$ 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

https://stackoverflow.com/a/19242713/6947646

answered Feb 28, 2017 at 9:40
2

sed is more applicable for the case than grep

sed '/\n/{P;D;};s/\[/\n/;s/\]/\n/;D' log
answered Feb 28, 2017 at 10:02
1
  • 1
    Hey, could you please explain what sed doing here. Thank you. Commented Sep 22, 2018 at 2:09
1

One way is piping to cut:

grep -oE "\[[0-9].+\]" logfile | cut -d'[' -f2 | cut -d']' -f1
answered Feb 28, 2017 at 9:40
1

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 [ and ].

answered Feb 28, 2017 at 9:45
1
  • Yes , i tried that as well and same answer already posted as comment by @Costas Commented Feb 28, 2017 at 9:45

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.