1

The below is my input file, say input.json

{
  "server1": {
    "name": "server1",
    "property": "ENABLED"
  },
  "server2": {
    "name": "server2",
    "property": "ENABLED"
  },
  "server3": {
    "name": "server3",
    "property": "ENABLED"
  },
  "server4": {
    "name": "server4",
    "property": "ENABLED"
  },
  "server5": {
    "name": "server5",
    "property": "ENABLED"
  },
  "server6": {
    "name": "server6",
    "property": "ENABLED"
  }
}

I am running the following jq query:

jq -r '.[] | select(.property == "ENABLED") |.name' input.json

I get the below output:

server1
server2
server3
server4
server5
server6

I want my output to be without any new line and as below, separated by space and no space after the last word (server6 in this case)

server1 server2 server3 server4 server5 server6

I don't want to do pipe after jq command and obtain the output with sed and tr commands. I want to achieve this with jq command only. Would appreciate the help. thanks.

Zack
  • 2,078
  • 10
  • 33
  • 58
  • Not sure if they're actual duplicates, but they seem close: https://stackoverflow.com/questions/44133851/how-to-get-the-output-of-jq-in-single-line https://stackoverflow.com/questions/46131727/printing-multiple-values-on-the-same-line – Barmar Aug 04 '20 at 00:53

1 Answers1

4

You're pretty close to there! In your case, the join function may help:

jq -r '[.[]|select(.property=="ENABLED")|.name]|join(" ")' input.json

By wrapping all names in an array, the join function works like that in python. From the doc:

join(str)

Joins the array of elements given as input, using the argument as separator. It is the inverse of split: that is, running split("foo") | join("foo") over any input string returns said input string.

jq ´join(", ")´
   ["a","b,c,d","e"]
=> "a, b,c,d, e"
dibery
  • 2,760
  • 4
  • 16
  • 25
  • awesome. I tried join before but it did not give me the output I expected because I had not wrapped it in an array. Thank you. – Zack Aug 04 '20 at 01:44