Create text reading data from a file

csvscripting

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?

Best Answer

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

Related Question