Writing a regular expression with a specific pattern sed / awk / perl

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

The regex pattern \[(.*)\]

for the next line, I want to capture group 1, which means anything in between[]

Processing record with rowkey [fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules

      

This is what I am trying to achieve, the above line is simple input. Below is a simple output:

fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1

      

Update question:

Actual data entry (sorry for omming not knowing it was necessary and a little more complicated):

Processing record with rowkey [fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules [[COUNT_ALL]].

      

+3


source to share


4 answers


You are experiencing greed problems .

Hence, you meet:

fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules [[COUNT_ALL]

      

instead:



fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1

      

Remember: matching .*

is greedy. (corresponds to the longest possible range)

Possible solutions:

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

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

  • just matching words: ( [A-Za-z_]

    )
    \[(\w*)\]

+5


source


$ echo 'Processing record with rowkey [fdebae87f9b7bcb7f698a0723cd1474b3a84bbb1] with these rules' | command_bellowing

      

SED

$ sed -r 's/.*\[(.*)\].*/\1/'

      

simpleton



$ gawk '{print gensub(/.*\[(.*)\].*/, "\\1", "g")}'

      

Perl

$ perl -ne 's/.*\[(.*)\].*/\1/;print'

      

+2


source


As Alex said, you captured him. If you want the result, try:

s/\[(.*)\]/$1/

0


source


This might work for you:

sed 's/^[^[]*\[\([^]]*\).*/\1/' file

      

0


source







All Articles