I have the following input:
{"_id":{"$oid":"5a62094b2213930f39856faa"},"zip":"68137","visit_date":{"$date":"2017-11-28T15:36:00.000Z"},"phone":"402-000-0819","city":"Omaha","state":"NE","gender":"female","dob":{"$date":"2018-01-19T00:00:00.000Z"},"firstname":"Joshua","user_ip":"42.668.23.195","lastname":"Maestle","done":1.0
{"_id":{"$oid":"5a62094b2213930f39856fb4"},"zip":"85013","visit_date":{"$date":"2017-11-28T11:32:00.000Z"},"city":"Phoenix","state":"AZ","gender":"male","dob":{"$date":"2018-01-19T00:00:00.000Z"},"firstname":"Andre","lastname":"Lippens","done":1.0
{"_id":{"$oid":"5a62094b2213930f39856fbc"},"zip":"70535","visit_date":{"$date":"2017-11-28T17:07:00.000Z"},"phone":"000-305-1888","city":"Eunice","state":"LA","gender":"male","user_ip":"12.158.33.145","dob":{"$date":"2018-01-19T00:00:00.000Z"},"firstname":"Derek","lastname":"Moore"
I need to extract the value for the IP field from each line. For lines where no IP field is present, I would like to print a blank line.
Desired output:
42.668.23.195
12.158.33.145
I have attempted this with:
grep -o -P '(?<="user_ip":").*(?=")'
But sadly this does not preserve the blank second line.
CodePudding user response:
If it doesn't have to be grep, here's a simple option:
perl -lpe '/"user_ip":"(.*?)"/; $_ = $1'
CodePudding user response:
grep does not have that functionality but you could use this simple Perl program to do it:
perl -nle'print /"user_ip":"(. ?)"/ ? $1 : ""' datafile.json