Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string from brackets

Tags:

bash

sed

I'm pretty new at bash so this is a pretty noob question..

Suppose I have a string:

string1 [string2] string3 string4 

I would like to extract string2 from the square brackets; but the brackets may be surrounding any other string at any other time.

How would I use sed, etc, to do this? Thanks!

like image 291
Dang Khoa Avatar asked Aug 26 '11 19:08

Dang Khoa


People also ask

How do I extract text from brackets in Excel?

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 text from 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 you get a string between two brackets in Python?

Use re.search() to get a part of a string between two brackets. Call re.search(pattern, string) with the pattern r"\[([A-Za-z0-9_]+)\]" to extract the part of the string between two brackets.

What do brackets do in grep?

A bracket expression is a list of characters enclosed by ' [ ' and ' ] '. It matches any single character in that list. If the first character of the list is the caret ' ^ ', then it matches any character not in the list, and it is unspecified whether it matches an encoding error.


2 Answers

Try this:

echo $str | cut -d "[" -f2 | cut -d "]" -f1 
like image 68
jman Avatar answered Oct 28 '22 04:10

jman


Here's one way using awk:

echo "string1 [string2] string3 string4" | awk -F'[][]' '{print $2}' 

This sed option also works:

echo "string1 [string2] string3 string4" | sed 's/.*\[\([^]]*\)\].*/\1/g' 

Here's a breakdown of the sed command:

s/          <-- this means it should perform a substitution .*          <-- this means match zero or more characters \[          <-- this means match a literal [ character \(          <-- this starts saving the pattern for later use [^]]*       <-- this means match any character that is not a [ character                 the outer [ and ] signify that this is a character class                 having the ^ character as the first character in the class means "not" \)          <-- this closes the saving of the pattern match for later use \]          <-- this means match a literal ] character .*          <-- this means match zero or more characters /\1         <-- this means replace everything matched with the first saved pattern                 (the match between "\(" and "\)" ) /g          <-- this means the substitution is global (all occurrences on the line) 
like image 26
Daniel Haley Avatar answered Oct 28 '22 04:10

Daniel Haley