Shell ${} and #,% Usage lufy May 02, 2018 <p>In shell scripts, symbols are very usefull to handle strings in variables. Next list some frequently used methods of getting specified strings from variables.</p> <p><span style="font-family: 'courier new', courier;">${var##*str}</span> get string after the last <span style="font-family: 'courier new', courier;">str</span> in <span style="font-family: 'courier new', courier;">$var</span></p> <p><span style="font-family: 'courier new', courier;">${var#*str} </span> get string after the 1st <span style="font-family: 'courier new', courier;">str</span> in <span style="font-family: 'courier new', courier;">$var</span></p> <p><span style="font-family: 'courier new', courier;">${var%%str*} </span> get string before the 1st <span style="font-family: 'courier new', courier;">str</span> in <span style="font-family: 'courier new', courier;">$var</span></p> <p><span style="font-family: 'courier new', courier;">${var%str*} </span> get string before the last <span style="font-family: 'courier new', courier;">str</span> in <span style="font-family: 'courier new', courier;">$var</span></p> <p><span style="font-family: 'courier new', courier;">${#var} </span> get how many bytes in <span style="font-family: 'courier new', courier;">$var</span>.</p> <p><strong>E.g.</strong></p> <p><span style="font-family: 'courier new', courier;">var=abcddcba</span></p> <p><span style="font-family: 'courier new', courier;">echo ${var##*c}</span> get "ba"</p> <p><span style="font-family: 'courier new', courier;">echo ${var#*c}</span> get "ddcba"</p> <p><span style="font-family: 'courier new', courier;">echo ${var%%c*} </span> get "ab"</p> <p><span style="font-family: 'courier new', courier;">echo ${var%c*} </span> get "abcdd"</p> <p><span style="font-family: 'courier new', courier;">echo ${#var} </span> get "8"</p>
Comments (0)
Leave a Comment
No comments yet. Be the first to comment!