Reputation: 25
I'm trying to extract the balance from this string (which I did already) and add a comma to the string like 6841,12691421 (already done that also) BUT! theres a problem with doing it the way I did.
{
"address": "NKNXyCmatuYuAnMFufdDnLL82qmvgB4uAYt6",
"count_transactions": 59606,
"first_transaction": "2020-08-07 17:25:51",
"last_transaction": "2021-05-02 09:09:24",
"balance": 684112691421,
"name": []
}
I did it with (excuse the noob code):
sed -n -r 's/(^.*balance":)([^"]+)".*/\2/p' | sed -e 's/[",]//g' | sed 's/./&,/4'
The problem:
The sed 's/./&,/4'
is a static thing. When the balance is lower by one character the output is wrong then, example `68411269142 the balance should be 684,11269142.
I need a solution to count the comm`a insert place from the right, 8 characters in.
Upvotes: 1
Views: 85
Reputation: 116880
Two jq-only solutions:
a) without any regex overhead:
jq -r '.balance | tostring | .[:-8]+ ","+ .[-8:]'
b) with regex:
jq -r 'tostring|sub("(?<tail>[0-9]{8}$)"; ",\(.tail)" )'
Unfortunately these jq-only solutions will only work reliably for integers with fewer than 16 digits unless you have a sufficiently recent version of jq (after 1.6).
Upvotes: 2
Reputation: 88776
With jq
and sed
:
jq '.balance' file.json | sed -E 's/.{8}$/,&/'
Output:
6841,12691421
Upvotes: 1
Reputation: 785631
You may use this single sed
:
sed -E 's/(^.*balance":)([^",]+).*/\2/; s/[0-9]{8}$/,&/' file
6841,12691421
s/[0-9]{8}$/,&/
matches 8 trailing digits and inserts a comma before itUpvotes: 1