What about:
shell_variable=$(sed -ne '/\[/,/\]/{s/^.*\[//;s/\].*//;p;}' $file)
Worked for me on Solaris 10 under the Korn shell; should also work with bash. Replace ' $(...) ' with back ticks in the Bourne shell.
Edit: worked when given [on one line and] on another. For a single line case, use:
shell_variable=$(sed -n -e '/\[[^]]*$/,/\]/{s/^.*\[//;s/\].*//;p;}' \ -e '/\[.*\]/s/^.*\[\([^]]*\)\].*$/\1/p' $file)
The first " -e " refers to multi-line distribution; the second " -e " deals with a single-line case. The first " -e " says:
- From a line containing an open parenthesis
[ followed by no closing bracket ] in the same line - As long as the string containing the closed bracket
] , - replace everything before and including the open bracket with an empty string,
- replace any of the closing brackets with an empty string and
- print the result
The second " -e " says:
- For any line containing both open and closed brackets
- Replace the pattern consisting of “characters before and including the open bracket”, “characters before, but excluding the closed bracket” (and keep this in mind), “material from the closed bracket forward” with catchy characters in the middle and
- print the result
For multi-line case:
$ file=xxx $ cat xxx sdsajdlajsdl asdajsdkjsaldjsal sdasdsad [aaaa bbbbbbb cccc] asdjsalkdjsaldjlsaj asdjsalkdjlksjdlaj asdasjdlkjsaldja $ shell_variable=$(sed -n -e '/\[[^]]*$/,/\]/{s/^.*\[//;s/\].*//;p;}' \ -e '/\[.*\]/s/^.*\[\([^]]*\)\].*$/\1/p' $file) $ echo $shell_variable aaaa bbbbbbb cccc $
And for a single line case:
$ cat xxx sdsajdlajsdl asdajsdkjsaldjsal sdasdsad [aaaa bbbbbbb cccc] asdjsalkdjsaldjlsaj asdjsalkdjlksjdlaj asdasjdlkjsaldja $ $ shell_variable=$(sed -n -e '/\[[^]]*$/,/\]/{s/^.*\[//;s/\].*//;p;}' \ -e '/\[.*\]/s/^.*\[\([^]]*\)\].*$/\1/p' $file) $ echo $shell_variable aaaa bbbbbbb cccc $
Somewhere here, simplifying all of Perl’s work, cutting out a file, and editing the resulting string in two multi-line replace operations.
Jonathan leffler
source share