Reputation: 1642
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
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
Reputation: 10039
echo "${OUTPUT}" | sed -e '/.*, code \([^,]\{1,\}\).*/ !d' -e 's//\1/'
posix compliant, so will work on any recent sed
Upvotes: 0