2

Input: I have a filename called 'myseedips' with a set of Ip addresses in it in the below structure

10.204.99.15
10.204.99.12
10.204.99.41

These can be 'n' number of IP addressess line by line.

Output I have no idea on bash programming. But I have to write a bash script to create a JSON file in the below structure. These IP addresses has to be in a loop, so that the JSON will change/extend depending on the length of myseedips file.

"cassandra": {
        "nodes": [
         {"ip_address": "10.204.99.15","type": "seed"},
         {"ip_address": "10.204.99.12","type": "seed"},
         {"ip_address": "10.204.99.41","type": "seed"}]
    },

Also need to add logic to add comma at the end of each node for all nodes except the last. Do not append comma if there is only one node.

Example: May be be something like the below code logic, but in bash programming.

j string
j = `"cassandra": {"nodes": [`
for i =0;i<len(ips);i++ {
    j = j + `{"ip_address": "` + ips[i] + `","type": "seed"},`
}
j = j + `}]}`

Thanks Nissar Sheik

Nissar
  • 23
  • 1
  • 1
  • 4

3 Answers3

2

Further to Jeff's answer, please note that the transformation can be accomplished with a single invocation of jq. If your jq has the inputs filter:

jq -Rn '[inputs] | {cassandra:{nodes:map({ip_address:.,type:"seed"})}}' 

Otherwise:

jq -Rs 'split("\n") | {cassandra:{nodes:map({ip_address:.,type:"seed"})}}' ips.txt
peak
  • 105,803
  • 17
  • 152
  • 177
1

awk to the rescue!

a template awk solution can be

$ awk 'BEGIN{print "header"} 
     NR==FNR{c=NR;next} 
            {print "prefix",$1,"suffix" (FNR<c?",":"]")}
         END{print "footer"}' myseedips{,}

header
prefix 10.204.99.15 suffix,
prefix 10.204.99.12 suffix,
prefix 10.204.99.41 suffix]
footer

you can replace the header,footer,prefix, and suffix.

karakfa
  • 66,216
  • 7
  • 41
  • 56
1

Using jq, you'll need an extra pass to convert from raw text to a workable array but simple:

$ jq -R '.' myseedips | jq -s '{cassandra:{nodes:map({ip_address:.,type:"seed"})}}'

This yields the following:

{
  "cassandra": {
    "nodes": [
      {
        "ip_address": "10.204.99.15",
        "type": "seed"
      },
      {
        "ip_address": "10.204.99.12",
        "type": "seed"
      },
      {
        "ip_address": "10.204.99.41",
        "type": "seed"
      }
    ]
  }
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272