Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the content between two brackets?

Tags:

My input:

   1:FAILED      +  *1      0     (8328832,AR,UNDECLARED) 

This is what I expect:

8328832,AR,UNDECLARED 

I am trying to find a general regular expression that allows to take any content between two brackets out.

My attempt is

  grep -o '\[(.*?)\]' test.txt > output.txt 

but it doesn't match anything.

like image 890
frankdede Avatar asked Aug 13 '13 20:08

frankdede


People also ask

How do I extract text between brackets?

Extract Text Between Parenthesis To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.

How do I extract data between brackets in Python?

The simplest way to extract the string between two parentheses is to use slicing and string. find() . First, find the indices of the first occurrences of the opening and closing parentheses. Second, use them as slice indices to get the substring between those indices like so: s[s.

How do I extract text between two delimiters in Excel?

The easiest way to extract a substring between two delimiters is to use the text to column feature in Excel, especially if you have multiple delimiters. In this example, use =MID(A2, SEARCH(“-“,A2) + 1, SEARCH(“-“,A2,SEARCH(“-“,A2)+1) – SEARCH(“-“,A2) – 1) in cell B2 and drag it to the entire data range.


1 Answers

Still using grep and regex

grep -oP '\(\K[^\)]+' file 

\K means that use look around regex advanced feature. More precisely, it's a positive look-behind assertion, you can do it like this too :

grep -oP '(?<=\()[^\)]+' file 

if you lack the -P option, you can do this with perl :

perl -lne '/\(\K[^\)]+/ and print $&' file 

Another simpler approach using awk

awk -F'[()]' '{print $2}' file 
like image 180
Gilles Quenot Avatar answered Oct 19 '22 11:10

Gilles Quenot