One 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 cutter.
Using the rematch feature of sed, you replace the entire string in question only with the required excerpts, with a unique separator between them, as a semicolon:
> RESULT='{"success":false,"errorCode":3,"message":"Authenticity Token invalido"}';
> echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/;/';
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
and
. 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 read
, all in one operation:
> IFS=';' read SUCCESS MESSAGE <<< $(echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/;/');
> echo $SUCCESS;
false
> echo $MESSAGE;
Authenticity Token invalido
If you prefer you can, of course, run two sed
as you did in the question:
> SUCCESS=$(echo $RESULT | sed -r 's/\{"success":(true|false).*//');
> MESSAGE=$(echo $RESULT | sed -r 's/.*"message":"(.*)"\}//');
> echo $SUCCESS;
false
> $MESSAGE;
Authenticity Token invalido