Home > Software engineering >  Pass multiple regular expressions to the gsub() function in jq
Pass multiple regular expressions to the gsub() function in jq

Time:11-13

How can I avoid doing embarrassing stuff like this when trying to apply multiple regular expressions using the gsub() function in jq?

."values" | tostring | gsub("\"";"`") | gsub("\\[";"") | gsub("\\]";"") | gsub("=\\w*";"")

I want to convert the array below to a string, keep the values to the left of the equals sign and surround each value in backticks.

The jq command above works but something tells me there's a more elegant solution.

Input:

{
  "values": [
    "1=foo",
    "2=bar",
    "3=baz"
  ]
}

Output (expected and actual)

"`1`,`2`,`3`"

CodePudding user response:

.values | map("`\(split("=") | first)`") | join(",")

JqPlay Demo

CodePudding user response:

Yet you can use gsub() such as

."values" | map("`\(gsub("=\\w ";""))`")| join(",")

Demo

CodePudding user response:

.values
| map(capture( "(?<key>^[^=]*)=" ).key | "`\(.)`" ) 
| join(",")
  • Related