'How to take string format from command line?
https://stedolan.github.io/jq/manual/#Stringinterpolation-%5C(foo)
I want to pass string format from the command line of jq, instead of embedding the format in string interpolation.
Let's say the format string is "my string %s". How to modify the following jq command to take the format string in its argument so that the output will be "my string x"?
jq --arg format "my string %s" -r -e . <<< '"x"'
Solution 1:[1]
Put your (dynamic) jq expression inside \(…), which in turn is part of a (static) string expression "…". If all you want is passing on the input, use the identity function ., and your example should read
jq -r -e '"my string \(.)"' <<< '"x"'
my string x
Having "my string %s" as a parameter string, you cannot use it for string interpolation, as string interpolation is a language construct, and jq does not provide an eval (or similar) function to evaluate a variable's content as code.
What you can do instead is to (naively) replace %s with something else using sub or gsub:
jq -r -e -n --arg f "my string %s" '$f | sub("%s"; input)' <<< '"x"'
my string x
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
