'remove a substring from a string

I want to remove , from a string in jq. Take the following example, how to remove , when outputting 1,2?

$ jq -r .x <<< '{"x":"1,2"}'
1,2
jq


Solution 1:[1]

To remove specific positions from a string, use the indices you want to keep:

jq -r '.x | .[:1] + .[2:]' <<< '{"x":"1,2"}'
12

Demo

To remove one occurrence at any position, use sub to replace with the empty string

jq -r '.x | sub(","; "")' <<< '{"x":"1,2,3"}'
12,3

Demo

To remove all occurrences, use gsub the same way

jq -r '.x | sub(","; "")' <<< '{"x":"1,2,3"}'
123

Demo

Solution 2:[2]

You didn't make clear what output you wanted. A literal reading suggests you want 12, but I find it more likely that you want each of the comma-separated items to be output on separate lines. The following achieves this:

jq -r '.x | split(",")[]'

For the provided input, this outputs

1
2

Demo on jqplay

Solution 3:[3]

You can use sub.

Filter

.x | sub(","; " ")

Input

{"x":"1,2"}

Output

1 2

Demo

https://jqplay.org/s/IaViogZTsI

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 pmf
Solution 2 ikegami
Solution 3 Logan Lee