Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing regex with certain pattern sed/awk/perl

Tags:

sed

awk

perl

How can I capture group 1 of the pattern below with any of the following(sed, awk, perl) ?

Regex pattern is \[(.*)\] for the below line, I want to capture group 1, meaning anything between []

Processing record with rowkey [fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules

Here is what I'm trying to achieve, above row is the simple input. Below is simple output:

fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1

Question Update :

Actual sample input is(sorry for ommiting didn't know it was necessary and bit more complex) :

Processing record with rowkey [fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules [[COUNT_ALL]].
like image 954
Gandalf StormCrow Avatar asked Dec 14 '25 15:12

Gandalf StormCrow


1 Answers

You're experiencing greediness issues.

Hence you're matching:

fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules [[COUNT_ALL]

instead of:

fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1

Remember: .* matching is greedy. (matches the longest possibile span)

Possible solutions:

  • reducing greediness: (not on sed and awk IIRC)
    \[(.*?)\]

  • reducing greediness the old way:
    \[([^\]]*)\]

  • just matching word characters: ([A-Za-z_])
    \[(\w*)\]

like image 78
ZJR Avatar answered Dec 16 '25 05:12

ZJR