Skip to content
Latchkey

jq gsub and sub : Regex Replace in Strings

jq gsub(re; repl) replaces every regex match in a string; sub(re; repl) replaces only the first.

Stripping a v prefix from a tag or rewriting a ref into a slug is a one-liner with gsub before feeding a value to a later step.

What it does

gsub(regex; replacement) substitutes all matches; sub does the first only. The regex uses Oniguruma syntax and the replacement can reference named captures like "(?<n>...)" via "\(.n)". A third flags argument such as "i" enables case-insensitivity.

Common usage

Terminal
# strip a leading v from a tag
jq -r '.tag_name | sub("^v"; "")' release.json
# slugify a branch ref
jq -r '.ref | gsub("[^a-zA-Z0-9]+"; "-")' event.json
# case-insensitive replace
echo '"Hello World"' | jq 'gsub("world"; "CI"; "i")'

Functions

FunctionWhat it does
gsub(re; r)Replace all matches
sub(re; r)Replace the first match
gsub(re; r; "i")Case-insensitive flag
"\(.name)"Reference a named capture in the replacement

Common errors in CI

"jq: error: <stdin>:0: gsub input must be a string" means the field is not a string; coerce with tostring. "jq: error: ... invalid regex" or "premature end of char-class" means an unescaped metacharacter; escape it or wrap the literal. Remember the args are separated by ; not ,.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →