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?

  • yes repeated with each new number it reads from a separate file – WMK83 Jul 9 '17 at 18:46
  • or maybe, it would be enough to get the result as a one main object – RomanPerekhrest Jul 9 '17 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 Jul 16 '17 at 12:37
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.