Blink
Blink

Reputation: 1504

Replace end of varying string

I have tried dozens of various sed options but haven't found a combination that works yet. I am trying to turn:

test(3) = var
other(8) = var
test(13) = var
...

into:

test(3) = newvar
other(8) = var
test(13) = newvar
...

The problem I'm encountering is the varying value in the parentheses. I want to edit after the value, to prevent having to catch it and assign it. I tried the following, thinking I could use .* as a wildcard inside the parentheses, but I can't seem to get it to work.

sed -n "s/\(test(.*\)\s+\w+/\1) = newstuff/g" file.txt

Upvotes: 1

Views: 73

Answers (1)

anubhava
anubhava

Reputation: 786339

You can use this sed command:

sed -i.bak 's/^\([^=]* *= *\).*$/\1newvar/' file

This will match RHS string (from start until = is found) and that is replaced by newvar

If you want to use a shell variable then use double quotes:

NEWVAR="something"
sed -i.bak "s/^\([^=]* *= *\).*$/\1$NEWVAR/" file

UPDATE: To change only lines starting with test:

sed -i.bak "s/^\( *test *[^=]* *= *\).*$/\1$NEWVAR/" file

Upvotes: 3

Related Questions