alexandernst
alexandernst

Reputation: 15099

Replacing regex groups with sed

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=''".

Upvotes: 15

Views: 21402

Answers (3)

Jotne
Jotne

Reputation: 41460

Here is a simple way to do it in awk

echo "this is a sample id='42' string" | awk -F\' '{$2=1}1' OFS=\'
this is a sample id='1' string

It does use ' as field separator and then just replace value in field #2

This should work too:

awk -F\' '$2=1' OFS=\'

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

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

Upvotes: 18

Mad Physicist
Mad Physicist

Reputation: 114548

In sed, the entire left regex is relpaced by the entire right regex. If you would like to preserve a portion of the left regex, you must explicitly copy it to the right or make it a capturing group as well:

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

will correctly replace all of the match, id='42', with 421 since \1 is 42. If you want to preserve the part that says id=..., you have to put it in the replacement:

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

Upvotes: 5

Related Questions