72

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!

9 Answers 9

108

Try this:

echo $str | cut -d "[" -f2 | cut -d "]" -f1
1
  • 7
    just to make sure I understand what's going on here (again, pretty noob at shell scripting: the first cut saves everything to the right of the [, and the second saves everything to the left of ]; those two together give me the string I want.
    – Dang Khoa
    Commented Aug 26, 2011 at 19:39
86

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)
4
  • This certainly works, but could you please explain what's going on?
    – Dang Khoa
    Commented Aug 26, 2011 at 19:43
  • 4
    Sure. I'll add an explanation to the answer. Commented Aug 26, 2011 at 19:54
  • 1
    @strictlyrude27 - i also added an example of using awk. It's similar to the accepted answer, but cleaner in my opinion. Commented Aug 26, 2011 at 20:10
  • Why do we need to escape the brackets that group the sub-string of the matched string? Also, I thought that the closing square-bracket inside the character class has to be escaped, but only works without that!! I could not understand this.
    – appanponn
    Commented May 20, 2014 at 10:19
25

In pure bash:

STR="string1 [string2] string3 string4"
STR=${STR#*[}
STR=${STR%]*}
echo $STR
2
  • 1
    Would it be possible to obtain [string2] (extracting too the brackets) by using this shell operation method? Commented Feb 1, 2015 at 2:33
  • Yes. To get what's inside the brackets, including the brackets, do the following: STR="[${STR#*[}", that removes everything before the bracket, then STR="${STR%]*}]", which removes everything after the bracket. The variable expansion removes the bracket, so you add one back in, inside the quotes.
    – xizdaqrian
    Commented Apr 26, 2017 at 23:07
24

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}'
0
19

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]
2

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}'

2

Another awk:

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

1
  • Thanks for this. Have you any idea how to get the text between the outermost delimiters? So if the string is x = (b + (c - d)) then it should pull out b + (c - d). Thanks.
    – gbe
    Commented Mar 22, 2017 at 9:52
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.