Skip to content
Advertisement

How to grep string and show previous word in a Linux file

i have a file with a lot of IPs and each IP have an ID, like this:

"id":340,"ip":"10.38.6.25"
"id":341,"ip":"10.38.6.26"
"id":345,"ip":"10.38.6.27"
"id":346,"ip":"110.38.6.27"

Below this Ips and after these Ips the file have more information, its a output to an API call..

I need, grep a IP and then the command shows the id, just the number. Like this:

345

EDIT: More information, the ip will be different every time, i need to pass the IP by argument. I cant parse the IP to the syntax X/X/X/X…

any ideas?

Advertisement

Answer

If you want to look up a single IP, use this:

jq ".collection|.[]|select(.ip=="10.38.6.3").id" data.json

If you must set IP in an argument, then write a one-liner bash script like this:

jq ".collection|.[]|select(.ip=="$2").id" "$1"

And call it like this:

./script data.json 10.38.6.3
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement