3

I have a csv file which has a list of 600 numbers in the following format

442030580306

442030580307

I need it to output the file in one long file like the below from reading the numbers above

         "new-request-uri-user-part:442030580306": {
            "query_string": {
              "query": "new-request-uri-user-part:442030580306",
              "analyze_wildcard": true
            }
          },
          "new-request-uri-user-part:442030580307": {
            "query_string": {
              "query": "new-request-uri-user-part:442030580307",
              "analyze_wildcard": true
            }
          },

Any ideas how best to achieve this?

3
  • yes repeated with each new number it reads from a separate file
    – WMK83
    Commented Jul 9, 2017 at 18:46
  • or maybe, it would be enough to get the result as a one main object Commented Jul 9, 2017 at 19:22
  • Do any of the existing answers solve your problem? If so, please indicate so with the checkmark, or else let us know what's missing. Thank you!
    – Jeff Schaller
    Commented Jul 16, 2017 at 12:37

2 Answers 2

2

When we want eventually obtain a JSON data - jq is the right tool:

numbers.csv file contents:

442030580306
442030580307

jq solution:

jq -s '"new-request-uri-user-part:" as $pfx | reduce [.[]|tostring][] as 
        $n ({}; .[($pfx + $n)] |= {"query_string": {"query": ($pfx + $n), "analyze_wildcard": true }})' numbers.csv

The output:

{
  "new-request-uri-user-part:442030580306": {
    "query_string": {
      "query": "new-request-uri-user-part:442030580306",
      "analyze_wildcard": true
    }
  },
  "new-request-uri-user-part:442030580307": {
    "query_string": {
      "query": "new-request-uri-user-part:442030580307",
      "analyze_wildcard": true
    }
  }
}

  • "new-request-uri-user-part:" as $pfx - assigning the common phrase "new-request-uri-user-part:" to varible $pfx

  • reduce [.[]|tostring][] as $n ({}; ...) - performing the reduction operation upon the list of input numbers

2

Simply, with printf:

while read number
do
  printf '        "new-request-uri-user-part:%s": {
            "query_string": {
              "query": "new-request-uri-user-part:%s",
              "analyze_wildcard": true
            }
          },
' "$number" "$number"
done < input

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .