Jq: Working example of sub

Created on 11 Feb 2015  路  7Comments  路  Source: stedolan/jq

Could you add working example of sub usage in the documentation?
I tried tests from tests/all.test and wrote some even simpler, but I always get sub is not defined, even with this:
.[] | sub(","; ":")
["a,b,c", "d,e,f"]

docs

Most helpful comment

You have fallen in the main trap in jq: the comma IS NOT an arguments separator in function calls.
Allways use the semi-colon!

All 7 comments

@damirda - Unfortunately the online manual documents some features that were only added after the release of jq 1.4. To use sub you will need to install a more recent version -- I would suggest anything after Oct 6 2014. Please see the Download page (http://stedolan.github.io/jq/download); additional notes are available on the jq wiki at https://github.com/stedolan/jq/wiki/Installation

Please note that the substrate of sub and gsub is taken from the input, and so:

$ jq -n '"abc" | sub("a"; "A")' 
"Abc"

There are some additional notes at
https://github.com/stedolan/jq/wiki/FAQ#support-for-regular-expressions

866 will make it easier to find documentation for released versions instead of looking at documentation for the upcoming release.

I'm having trouble extending your example to something that reads from stdin. e.g. what am I doing wrong here?

$ jq '.key |= sub("a", "A")' <<< '{"key":"abc"}'
jq: error: sub/1 is not defined at <top-level>, line 1:
.key |= sub("a", "A")       
jq: 1 compile error

You have fallen in the main trap in jq: the comma IS NOT an arguments separator in function calls.
Allways use the semi-colon!

@fadado doh! thanks.

Has anyone a reshuffeling sample with multiple regex matches?

The jq FAQ has this example, which illustrates a technique which could be used for "shuffling":

$ jq -n '"abc" | sub( "(?<head>^.)(?<tail>.*)"; "\(.head)-\(.tail)")'
"a-bc"
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  4Comments

geoffeg picture geoffeg  路  3Comments

rubensayshi picture rubensayshi  路  3Comments

lhunath picture lhunath  路  3Comments

sloanlance picture sloanlance  路  3Comments