Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What about:</p> <pre><code>shell_variable=$(sed -ne '/\[/,/\]/{s/^.*\[//;s/\].*//;p;}' $file) </code></pre> <p>Worked for me on Solaris 10 under Korn shell; should work with Bash too. Replace '<code>$(...)</code>' with back-ticks in Bourne shell.</p> <p><em>Edit</em>: worked when given [ on one line and ] on another. For the single line case as well, use:</p> <pre><code>shell_variable=$(sed -n -e '/\[[^]]*$/,/\]/{s/^.*\[//;s/\].*//;p;}' \ -e '/\[.*\]/s/^.*\[\([^]]*\)\].*$/\1/p' $file) </code></pre> <p>The first '<code>-e</code>' deals with the multi-line spread; the second '<code>-e</code>' deals with the single-line case. The first '<code>-e</code>' says:</p> <ul> <li>From the line containing an open bracket <code>[</code> not followed by a close bracket <code>]</code> on the same line</li> <li>Until the line containing close bracket <code>]</code>,</li> <li>substitute anything up to and including the open bracket with an empty string,</li> <li>substitute anything from the close bracket onwards with an empty string, and</li> <li>print the result</li> </ul> <p>The second '<code>-e</code>' says:</p> <ul> <li>For any line containing both open bracket and close bracket</li> <li>Substitute the pattern consisting of 'characters up to and including open bracket', 'characters up to but excluding close bracket' (and remember this), 'stuff from close bracket onwards' with the remembered characters in the middle, and</li> <li>print the result</li> </ul> <p>For the multi-line case:</p> <pre><code>$ 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 $ </code></pre> <p>And for the single-line case:</p> <pre><code>$ 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 $ </code></pre> <p>Somewhere about here, it becomes simpler to do the whole job in Perl, slurping the file and editing the result string in two multi-line substitute operations.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload