V
V
vlarkanov2019-04-25 10:05:26
linux
vlarkanov, 2019-04-25 10:05:26

How to extract a substring from a string using grep?

There is a line received by curl:

{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags":"0"}],"id":1}

How to get the value of the groupid key from it - i.e. the number 63?
Made through cut, but very cumbersome and ugly.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Shitskov, 2019-04-25
@vlarkanov

echo '"{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags":"0"}],"id":1}"' | cut -d\" -f11
:

Cumbersome?
Better like this:
echo '{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags":"0"}],"id":1}' | jq -r '.result[0].groupid'
:

PS In general, it's easier to work with a jrpc server as a jrpc client, from the same python. Yes, even if you do not use the jrpc client implementation. You can also return an array of results here.

Q
qlkvg, 2019-04-25
@qlkvg

For a collection

echo "{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags":"0"}],"id":1}" | grep -oP "(?<=groupid:)[0-9]*"

S
Saboteur, 2019-04-25
@saboteur_kiev

How to get the value of the groupid key from it - i.e. the number 63?

Examples for MYSTRING:
MYSTRING='{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags": "0"}],"id":1}'
awk
grep
jq
variable expansion
cut
echo $MYSTRING|cut -d\" -f 10

E
Educated, 2019-04-26
@Educated

echo '{"jsonrpc":"2.0","result":[{"groupid":"63","name":"1voda","internal":"0","flags":"0"}] ,"id":1}' | grep -oP '(?<=groupid":")\d+'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question