0

How to take the number including dot from an output of one command and use it in another one?

For example, this command

chia wallet show -w standard_wallet

gives this result

Wallet height: xxxxxx
Sync status: Synced
Balances, fingerprint: xxxxxxx

Chia Wallet:
   -Total Balance:         0.192267662015 xch (192267662015 mojo)
   -Pending Total Balance: 0.192267662015 xch (192267662015 mojo)
   -Spendable:             0.192267662015 xch (192267662015 mojo)

I want to take the number 0.192267662015 from the Spendable line to use in another command which will become

chia wallet send -a 0.192267662015

There will only be one Chia Wallet section in the output, and only one Spendable line.

How to write a script to do this? I have been looking up to grep, sed and xargs but not sure how to put them in the use correctly.

1

1 Answer 1

1

Since you only have one Wallet section, and you want to use the Spendable amount, the following approach should work:

chia wallet send -a "$(chia wallet show -w standard_wallet | awk '$1=="-Spendable:"{print $2}')"

The idea is as follows:

  • The wallet send command receives its "amount" via command substitution (i.e. the $( ... ) is replaced by the output of the enclosed command).
  • The enclosed command is the wallet show command whose output is piped to an awk program for text processing.
  • The awk program will split the lines it receives from the wallet show command into "fields" at (contiguous) whitespace. It is designed to print the second field ($2) if the first field is equal to -Spendable:. Note that this approach works in this simplicity only because the "Key" is a single contiguous string without "internal" whitespace in this particular case.
  • As a result, the $( ... ) used as "value" for the -a option is replaced by 0.192267662015 for the above example.

Since this involves financial transactions, be sure to test the inner command (inside the $( ... )) before doing anything unrecoverable.


If you want to change the number of digits, you can use printf instead of print and use the "well-known" formatting options, e.g.:

awk '$1=="-Spendable:"{printf "%.4f\n",$2}'

If you want to force rounding down, you can truncate the string (as per a comment by Ed Morton):

print ((p=index($2,".")) ? substr($2,1,p+3) : $2)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.