Home > other >  Trying to get 1st ip address from a json file using jq to get expected output
Trying to get 1st ip address from a json file using jq to get expected output

Time:07-30

Below is the output I am trying to get from a json file. Can someone please help to get the expected output with line of code?

Note : JSON file can't be changed and I don't want to get the 2nd ip address in the output. shell/bash/awk/sed programs preferable.

JSON :

{"result":[{"description": "Validate application after update for expected operation\nVM Name: fldcldswps7175 \nManaged Instance ID: i-01a2asda390b99 \nIP Address: 10.199.157.67,10.199.157.68","status":true}, {"name":"XML", "good":false}]}

Output : 10.199.157.67

Tried Code : IPaddress=('.result'|grep "description"|grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'|sed 's/,*$//g'|tr -d ',') echo $IPaddress

CodePudding user response:

As jq is tagged, here's a solution using jq. It traverses in the JSON file to the value in .result[0].description, selects the last [-1] text line, applies the regex, and outputs the first [0] result.

jq --arg regex '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -r '
  .result[0].description | split("\n")[-1] | [scan($regex)][0]
' file.json 
10.199.157.67

Demo

CodePudding user response:

With your shown samples and attempts, please try following GNU grep command. Since OP mentioned external tools libraries can't be used for OP's system so using grep code here, though its always advised to use json aware tools itself.

grep -oP '^\{"result":\[.*IP Address: \K[^,]*' Input_file

Explanation: Using GNU grep's -oP options here, which will print matched data and enable PCRE regex flavor respectively. In main program using regex ^\{"result":\[.*IP Address: \K[^,]* where it will match values from starting {"result": to till string IP Address: then I am using \K option which will allow match to happen but will make sure its value is getting washed out so that values coming after \K only are getting printed. Then using [^,]* will catch ip address value everything just before 1st comma occurrence.

NOTE: This considers that your json is of one line like mentioned in comments.

  • Related