A way to solve this kind of thing with bash
is to use regular expressions to "clean" the return string and add separators that can then be treated with a cutting tool.
Using the functionality of rematch sed, you replace the entire string in question only with the necessary snippets, with a unique separator between them, such as semicolon:
> RESULT='{"success":false,"errorCode":3,"message":"Authenticity Token invalido"}';
> echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/\1;\2/';
false;Authenticity Token invalido
Using the parentheses in the regular expression, the content they surround is passed to the numeric variables of rematch, in the case \1
and \2
. So you’re replacing the entire string with these two variables, separated by the semicolon.
With this output string, you can assign it to different variables by setting the shell separator character equal to the chosen semicolon, and use the read
, all in one operation:
> IFS=';' read SUCCESS MESSAGE <<< $(echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/\1;\2/');
> echo $SUCCESS;
false
> echo $MESSAGE;
Authenticity Token invalido
If you prefer you can of course run two sed
as you asked in the question:
> SUCCESS=$(echo $RESULT | sed -r 's/\{"success":(true|false).*/\1/');
> MESSAGE=$(echo $RESULT | sed -r 's/.*"message":"(.*)"\}/\1/');
> echo $SUCCESS;
false
> $MESSAGE;
Authenticity Token invalido
To return true or false I managed to run awk twice: SUCCESS=$(echo $RESULT | awk -F ':' '/Success/ {print $2}' | awk -F ',' '/false|true/ {print $1}') .
– fdavid