'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
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
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
To remove all occurrences, use gsub the same way
jq -r '.x | sub(","; "")' <<< '{"x":"1,2,3"}'
123
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
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 |
