How can I capture the text between specific delimiters into a shell variable? How can I capture the text between specific delimiters into a shell variable? unix unix

How can I capture the text between specific delimiters into a shell variable?


Bash/sed:

VARIABLE=$(tr -d '\n' filename | sed -n -e '/\[[^]]/s/^[^[]*\[\([^]]*\)].*$/\1/p')

If that is unreadable, here's a bit of an explanation:

VARIABLE=`subexpression`      Assigns the variable VARIABLE to the output of the subexpression.tr -d '\n' filename  Reads filename, deletes newline characters, and prints the result to sed's inputsed -n -e 'command'  Executes the sed command without printing any lines/\[[^]]/             Execute the command only on lines which contain [some text]s/                   Substitute^[^[]*               Match any non-[ text\[                   Match [\([^]]*\)            Match any non-] text into group 1]                    Match ].*$                  Match any text/\1/                 Replaces the line with group 1p                    Prints the line


May I point out that while most of the suggested solutions might work, there is absolutely no reason why you should fork another shell, and spawn several processes to do such a simple task.

The shell provides you with all the tools you need:

$ var='foo[bar] pinch'$ var=${var#*[}; var=${var%%]*}$ echo "$var"bar


Sed is not necessary:

var=`egrep -o '\[.*\]' FILENAME | tr -d ][`

But it's only works with single line matches.