Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since it bugged me a lot I have asked directly on www.unix.com and was kindly provided with a solution which fits for my ancient shell. So if anyone got the same problem here is the solution:</p> <pre><code>line='aaaa$aa{yyy}aaa${important}xxxxxxxx${important2}oo{o$}oo$oo${importantstring3}' IFS=\$ read -a words &lt;&lt;&lt; "$line" regex='^(\{[^}]+})' for e in "${words[@]}"; do if [[ $e =~ $regex ]]; then echo "\$${BASH_REMATCH[0]}"; fi; done </code></pre> <p>which prints then the following - without even getting disturbed by random occurrences of <code>$</code> and <code>{</code> or <code>}</code> between the syntactically correct expressions:</p> <pre><code>${important} ${important2} ${importantstring3} </code></pre> <p>I have updated the full solution after I got another update from the forums: now it also ignores this: <code>aaa$aa{yyy}aaaa</code> - which it previously printed as ${yyy} - but which it should completely ignore as there are characters between <code>$</code> and <code>{</code>. Now with the additional anchoring on the beginning of the regexp it works as expected.</p> <p>I just found another issue: theoretically using the above approach I would still get a wrong output if the read line looks like this <code>line='{ccc}aaaa${important}aaa'</code>. The IFS would split it and the REGEX would match <code>{ccc}</code> although this hadn't the <code>$</code> sign in front. This is suboptimal.<br> However following approach could solve it: after getting the BASH_REMATCH I would need to do a search in the original line - the one I gave to the IFS - for this exact expression <code>${ccc}</code> - with the difference, that the <code>$</code> is included! And only if it finds this exact match, only then, it counts as a valid match; otherwise it should be ignored. Kind of a reverse search method...<br></p> <p>Updated - add this reverse search to ignore the trap on the beginning of the line:</p> <pre><code>pattern="\$${BASH_REMATCH[0]}"; searchresult=""; searchresult=`echo "$line" | grep "$pattern"`; if [ "$searchresult" != "" ]; then echo "It was found!"; fi; </code></pre> <p>Neglectable issue: If the line looks like this <code>line='{ccc}aaaaaa${ccc}bbbbb'</code> it would recognize the <em>first</em> <code>{ccc}</code> as a valid match (although it isn't) and print it, because the reverse search found the <em>second</em> <code>${ccc}</code>. Although this is not intended it's irrelevant for my specific purpose as it implies that this pattern does in fact exist at least once in the same line.</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