Haswell
Haswell

Reputation: 1642

shell: Extract key value from a string with known key

I have a script inside which the following command is run:

OUTPUT=`echo "User-Name=$username,User-Password=$passwd" | radclient $ip auth $key`
echo $OUTPUT

After executing the command I get the following result in OUTPUT.

Received response ID 239, code 2, length = 34
        Reply-Message = "Hello, root"

Then I check whether the OUPUT contains "code":

if grep -wq code <<< $OUTPUT; then    
    echo "Success"
    break;
fi

This also works.

Now if my OUTPUT variable contains code then I want to extract the code value: 2 (in above case)

How can this be achieved:

So Input:

Received response ID 239, code 2, length = 34
            Reply-Message = "Hello, root"

Output: 2

Upvotes: 1

Views: 1999

Answers (3)

Agoston Horvath
Agoston Horvath

Reputation: 791

You can do it directly in bash, it has regular expression support, in your case it could go something like this:

read A < <(echo 'Received response ID 239, code 2, length = 34')
if [[ "$A" =~ ^Received\ response\ ID\ [0-9]+,\ code\ ([0-9]+),\ length\ =\ ([0-9]+) ]]; then echo ${BASH_REMATCH[1]} - ${BASH_REMATCH[2]}; else echo nope; fi

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

echo "${OUTPUT}" | sed -e '/.*, code \([^,]\{1,\}\).*/ !d' -e 's//\1/'

posix compliant, so will work on any recent sed

Upvotes: 0

jvdm
jvdm

Reputation: 876

echo $OUTPUT | sed -n 's/.*code \([^,]\+\),.*/\1/p'

Upvotes: 2

Related Questions