Extract string from brackets

BashSed

Bash Problem Overview


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!

Bash Solutions


Solution 1 - Bash

Try this:

echo $str | cut -d "[" -f2 | cut -d "]" -f1

Solution 2 - Bash

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)

Solution 3 - Bash

In pure bash:

STR="string1 [string2] string3 string4"
STR=${STR#*[}
STR=${STR%]*}
echo $STR

Solution 4 - Bash

Specify awk multiple delimiters with -F '[delimiters]'

If the delimiters are square brackets, put them back to back like this ][

awk -F '[][]' '{print $2}'

otherwise you will have to escape them

awk -F '[\\[\\]]' '{print $2}'

Other examples to get the value between the brackets:

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

Solution 5 - Bash

Here's another one , but it takes care of multiple occurrences, eg

$ echo "string1 [string2] string3 [string4 string5]" | awk -vRS="]" -vFS="[" '{print $2}'
string2
string4 string5

The simple logic is this, you split on "]" and go through the split words finding a "[", then split on "[" to get the first field. In Python

for item in "string1 [string2] string3 [string4 string5]".split("]"):
    if "[" in item:
       print item.split("]")[-1]

Solution 6 - Bash

Another awk:

$ echo "string1 [string2] string3 [string4]" |
awk -v RS=[ -v FS=] 'NR>1{print $1}' 
string2
string4

Solution 7 - Bash

Read file in which the delimiter is square brackets:
$ cat file
123;abc[202];124
125;abc[203];124
127;abc[204];124

To print the value present within the brackets:
$ awk -F '[][]' '{print $2}' file
202
203
204

At the first sight, the delimiter used in the above command might be confusing. Its simple. 2 delimiters are to be used in this case: One is [ and the other is ]. Since the delimiters itself is square brackets which is to be placed within the square brackets, it looks tricky at the first instance.

Note: If square brackets are delimiters, it should be put in this way only, meaning first ] followed by [. Using the delimiter like -F '[[]]' will give a different interpretation altogether.

Refer this link: http://www.theunixschool.com/2012/07/awk-10-examples-to-read-files-with.html

Solution 8 - Bash

Here is an awk example, but I'm matching on parenthesis which also makes it more obvious of how the -F works.

> echo 'test (lskdjf)' | awk -F'[()]' '{print $2}'

Solution 9 - Bash

Inline solution could be:

a="first \"Foo1\" and second \"Foo2\""
echo ${a#*\"} | { read b; echo ${b%%\"*}; }

You can test in single line:

a="first \"Foo1\" and second \"Foo2\""; echo ${a#*\"} | { read b; echo ${b%%\"*}; }

Output: Foo1

Example with brackets:

a="first [Foo1] and second [Foo2]"
echo ${a#*[} | { read b; echo ${b%%]*}; }

That in one line:

a="first [Foo1] and second [Foo2]"; echo ${a#*[} | { read b; echo ${b%%]*}; }

Output: Foo1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDang KhoaView Question on Stackoverflow
Solution 1 - BashjmanView Answer on Stackoverflow
Solution 2 - BashDaniel HaleyView Answer on Stackoverflow
Solution 3 - BashAlex HowanskyView Answer on Stackoverflow
Solution 4 - BashoutdevView Answer on Stackoverflow
Solution 5 - Bashghostdog74View Answer on Stackoverflow
Solution 6 - BashdawgView Answer on Stackoverflow
Solution 7 - BashSudhir SinhaView Answer on Stackoverflow
Solution 8 - BashRobert SuttonView Answer on Stackoverflow
Solution 9 - BashLuca DavanzoView Answer on Stackoverflow