I have a json file
{"doc_type":"user","requestId":"1000778","clientId":"42114"}
I want to change it to
{"doc_type":"user","requestId":1000778,"clientId":"42114"}
i.e. convert the requestId from String to Integer. I have tried some ways, but none seem to work :
sed -e 's/"requestId":"[0-9]"/"requestId":$1/g' test.json sed -e 's/"requestId":"([0-9])"/"requestId":444/g' test.json
Could someone help me out please?
Advertisement
Answer
Try
sed -e 's/("requestId":)"([0-9]*)"/12/g' test.json
or
sed -e 's/"requestId":"([0-9]*)"/"requestId":1/g' test.json
The main differences with your attempts are:
Your regular expressions were looking for
[0-9]
between double quotes, and that’s a single digit. By using[0-9]*
instead you are looking for any number of digits (zero or more digits).If you want to copy a sequence of characters from your search in your replacing string, you need to define a group with a starting
(
and a final)
in the regexp, and then use1
in the replacing string to insert the string there. If there are multiple groups, you use1
for the first group,2
for the second group, and so on.
Also note that the final g
after the last /
is used to apply this substitution in all matches, in every processed line. Without that g
, the substitution would only be applied to the first match in every processed line. Therefore, if you are only expecting one such replacement per line, you can drop that g
.