Replacing regex groups with sed

bash, regex, sed

Solution

Maybe like this?

$ echo "this is a sample id='42' string" | sed -r "s/id='.*?'/id='1'/g"

Result:

this is a sample id='1' string

Or you can do this:

$ echo "this is a sample id='42' string" | sed -r "s/(id=')(.*?)(')/\11\3/g"
this is a sample id='1' string

Result:

this is a sample id='1' string

Problem

I'm trying to replace (with sed) a group matched with a regex, but the best I can get out of my tests is a string that replaces the entire string on the right side of the sed separator. Example: ``` echo "this is a sample id='42' string" | sed -r "s/id='(.*?)'/\11/g" ``` Output: ``` this is a sample 421 string ``` Desired output: ``` this is a sample id='1' string ``` Is this possible? How? EDIT: What I'm trying to do is to actually replace just the group matched by the regex, not the entire string on the left side of the sed script. Said with other words: I want to replace just the '42' with '1' without using "id=''".

Original source