How to extract a substring matching a pattern from a Unix shell variable How to extract a substring matching a pattern from a Unix shell variable shell shell

How to extract a substring matching a pattern from a Unix shell variable


bash can strip parts from the content of shell variables.

${parameter#pattern} returns the value of $parameter without the part at the beginning that matches pattern.

${parameter%pattern} returns the value of $parameter without the part at the end that matches pattern.

I guess there is a better way to do this, but this should work.So you could combine this into:

% strip the part before the value:test=${test#Msg }% strip the part after the value:test=${test%, Level*}echo $test

If you're interested in the (return status = xxx) part, it would be:

result=${test#*(result status = }result=${result%)*}echo $result

The relevant section of the bash manpage is "Parameter Expansion".


Here is a quick and dirty hack for you, though you should really start learning this stuff yourself:

RC=`tail -1 $test |sed 's/(return status = \([0-9]\+\))/\1/'`