-1

I'm trying to get a specific part of a command's output using bash. So when you run this command;

./xuez-cli getnetworkinfo

it gives you an output like this;

"localaddresses" : [
    {
        "address" : "snyc3vzezoch2jax.onion",
        "port" : 41798,
        "score" : 4
    }
]

and from this output, I need to get this address, snyc3vzezoch2jax.onion and put into into a text file or a variable.

The .onion part always stay the same, although the characters before it will be different each time so I need a general solution to get the whole address.

I've tried ./xuez-cli getnetworkinfo | grep address though it gave me this output;

"localaddresses" : [
        "address" : "snyc3vzezoch2jax.onion",

and still couldn't find a way to paste this address part into a text file or a variable.

How can I do that?

oguz ismail
  • 1
  • 16
  • 47
  • 69
Tolgahan Bozkurt
  • 373
  • 1
  • 4
  • 7
  • Welcome to SO. Stack Overflow is a question and answer site for professional and enthusiast programmers. The goal is that you add some code of your own to your question to show at least the research effort you made to solve this yourself. – Cyrus Nov 03 '18 at 11:44
  • 2
    Why not use a JSON parser? – melpomene Nov 03 '18 at 12:01

1 Answers1

1

You can use jq.

  • to assign the output to a variable:

    addr=$(./xuez-cli getnetworkinfo | jq -r '.localaddresses[0].address // "something other than null"')
    
  • to write output to a file:

    ./xuez-cli getnetworkinfo | jq -r '.localaddresses[0].address // "something other than null"' > addrfile
    
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • `jq -r` can probably cope, too. – tripleee Nov 03 '18 at 14:13
  • @tripleee Nope, it says `parse error: output produced at line 1, column 16` – oguz ismail Nov 03 '18 at 15:01
  • @oguzismail I've tried your code and it's returning this error; `parse error: Objects must consist of key:value pairs at line 41, column 1` @tripleee I've also tried `jq -r` like this; `addr=$(./xuez-cli getnetworkinfo | jq -r '.localaddresses[0].address')` and this one works, though it returns `null` if the command doesn't return anything and save it as string `null` into variable. do you know how can I fix this so it does something else maybe, in return of `null`? – Tolgahan Bozkurt Nov 03 '18 at 19:50
  • @Tolgahan updated my answer – oguz ismail Nov 03 '18 at 20:39