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

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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"
      }
    ]
  }
}

1 Comment

Jeff, would you also mind answering my one more question posted in this loop
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.