bashshellcommand-substitution

bash filename as parameter in jq commands


Here is the bash function to parse a json file use 'jq' command:

jq_fullpath_endkey() {
      PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")' **${news.json}**)
}

The news.json is the json file that contains all the content I'd like to parse with jq.

The function works once I replace ${news.json} with a variable named response which contains news.json content as string.

Below is the command which works:

  PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")'**<<< "$response"**)

My question is how can I use 'json file' as part of the jq cmd ? I suspect there is something wrong with double/single quote I am using.


Solution

  • I figure it out with "parameter substitution" in bash

    myfile="news.json"
    PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")' ${myfile})
    

    Related concepts: variable substitution command substitution