tags:

views:

185

answers:

1

I'd like to use the search pattern in the output part of a sed command. For instance, given the following sed command:

sed '/HOSTNAME=/cHOSTNAME=fred' /etc/sysconfig/network

I'd like to replace the second instance of "HOSTNAME=" with some escape sequence that references the search term. Something like this:

# this doesn't actually work
sed '/HOSTNAME=/c\?=fred' /etc/sysconfig/network

Does anywone know if there's a way to do this or do I have to repeat the search term in the answer.

I know I can do something like this:

sed 's/\(HOSTNAME=\)/\1fred/' /etc/sysconfig/network

But this is subtly different from what I want -- for instance #HOSTNAME=zug will turn into #HOSTNAME=fred, but I don't want the leading "#". The first sed example takes care of cases like this.

+2  A: 

Try these:

sed 's/.*\(HOSTNAME=\)/\1fred/' /etc/sysconfig/network

Or

sed 's/.*\(HOSTNAME=\).*/\1fred/' /etc/sysconfig/network
Dennis Williamson
While the second form does indeed do what I want -- I'm still hoping to find a way to repeat the pattern space in the output -- hopefully using the 'c' command instead of the 's' command as shown in the question.However, if there is no other answer, then this will be the accepted answer.
JohnnyLambada
You can move the match from the `s` command to the address, but that's unnecessary in this simple case. Here is what it would look like: `sed '/.*\(HOSTNAME=\).*/ s//\1fred/' /etc/sysconfig/network` The `c\ `, `a\ ` and `i\ ` only work with literal text, they do not do any *substitutions* - that's what the `s///` command is for.
Dennis Williamson
Ok, good enough -- thanks!
JohnnyLambada