Consider the situation:
echo '"field:bla"\n"field:"' \
| jq ' . | gsub( "^field:(?<val>. ?)?$" ; "(?(val)value=\(.val)|NULL)" )'
We're taking in a list of strings of the form: field:<VALUE>
, where <VALUE>
can be either ''
(empty), or one or more characters.
The objective is to return: NULL
if <VALUE>
is ''
(empty), or value=<VALUE>
if non-empty.
the question is, can jq
do this using conditional substitution ? based on whether or not the group <val>
is set ? if so what is the syntax ? or is this not supported ?
PS: it's not a problem of whether this can be done, or how to do it, i'm just wondering if jq's gsub supports conditional group substitution, and if so what's the right syntax for it.
CodePudding user response:
The closest you can get to a "conditional substitution" within sub
would be along these lines:
(echo "field:bla"; echo "field:") |
jq -rR 'sub( "^field:(?<val>.*)$" ; "value=\(.val | if length==0 then "NULL" else . end )" ) '
This produces:
value=bla
value=NULL
You might also like to consider this alternative, which produces the same result:
(echo "field:bla"; echo "field:") |
jq -rR 'sub( "^(field:(?<val>. )|field:)$" ; "value=\(.val // "NULL")" )'
In both these cases, replacing sub
by gsub
has no effect on the results.