Imagine I have two files as below:
file1:
[
"id1",
"id2"
]
file2:
[
{
"id": "id1",
"name": "name1"
},
{
"id": "id1",
"name": "name2"
},
{
"id": "id3",
"name": "name3"
},
{
"id": "id5",
"name": "name5"
},
{
"id": "id2",
"name": "name6"
}
]
I want to find those entries in file2 that their id exist in file1, in the example above the expected output should be like:
[
{
"id": "id1",
"name": "name1"
},
{
"id": "id1",
"name": "name2"
},
{
"id": "id2",
"name": "name6"
}
]
How can I achieve it with jq.
2
Answers
You’ll get better/more succinct answers, but this seems to work. Slurp both files into an array, use
file1.json
contents as a filter toreduce
file2.json
.Try it on jqplay.org.
If the file sizes are large, this might be better since it doesn’t slurp.
Try this on jqplay.org.
Both output:
With both inputs already being arrays, there’s no need to
--slurp
. Also, as there are exactly two inputs, there’s also no need to call on--null-input
, just useinput
for the second one. For example, using the inputs in reversed order:Demo