tags:

views:

255

answers:

3

This is similar to a question that has already been asked. However, I am looking for a Sed specific answer. I have text similar to the following:

Some sample text [with some extra text].foo

I need to grab just the text inside the brackets. My attempts thus far have been futile. I can parse the line with other tools but I can't seem to get Sed to parse it correctly.

+1  A: 

Here is an example the replaces the text inside brackets:

$ echo 'Some sample text [with some extra text].foo' | sed -e 's/\[\(with some extra text\)\]/<\1>/g'
Some sample text <with some extra text>.foo
dmitry_vk
+2  A: 

Something like this?

$ echo Some sample text [with some extra text].foo | sed -e 's/.*\[\([^]]*\)\].*/\1/g'
with some extra text

$ echo Some sample text [with some extra text].foo | sed -e 's/.*\[\([^]]*\)\].*/Your text was: "\1", okay?/g'
Your text was: "with some extra text", okay?
Stobor
The key point in this answer is the use of single quotes around the sed expression - something that should have been stated in the answer. It is crucial; otherwise, the shell removes the backslashes and sed 'sees' expressions without them, and doesn't interpret it the way you'd like it to.
Jonathan Leffler
A: 
echo "Some [sample inside] text [with some extra text].foo" | sed -n '/\[/{ s/\]/\n/g; s/.[^\n]*\[/:/g;s/\..*//;p}'
:sample inside:with some extra text