tags:

views:

1757

answers:

5

How can one replace a part of a line with sed?

The line

DBSERVERNAME     xxx

should be replaced to:

DBSERVERNAME     yyy

The value xxx can vary and there are two tabs between dbservername and the value. This name-value pair is one of many from a configuration file.

I tried with the following backreference:

echo "DBSERVERNAME    xxx" | sed -rne 's/\(dbservername\)[[:blank:]]+\([[:alpha:]]+\)/\1 yyy/gip'

and that resulted in an error: invalid reference \1 on `s' command's RHS.

Whats wrong with the expression? Using GNU sed.

A: 

You're escaping your ( and ). I'm pretty sure you don't need to do that. Try:

sed -rne 's/(dbservername)[[:blank:]]+\([[:alpha:]]+\)/\1 yyy/gip'
apandit
A: 

You shouldn't be escaping things when you use single quotes. ie.

echo "DBSERVERNAME    xxx" | sed -rne 's/(dbservername[[:blank:]]+)([[:alpha:]]+)/\1 yyy/gip'
Matthew Scharley
A: 

You shouldn't be escaping your parens. Try:

echo "DBSERVERNAME    xxx" | sed -rne 's/(dbservername)[[:blank:]]+([[:alpha:]]+)/\1 yyy/gip'
Pesto
+2  A: 

This works:

sed -rne 's/(dbservername)\s+\w+/\1 yyy/gip'

(When you use the -r option, you don't have to escape the parens.)

Jeremy Stein
+2  A: 

Others have already mentioned the escaping of parentheses, but why do you need a back reference at all, if the first part of the line is constant?

You could simply do

sed -e 's/dbservername.*$/dbservername yyy/g'
Vicky
Good point! I had just learnt about using regexps + sed and mind just decided 'regexp' on seeing this particular task, then as 'jwz' said 'I had two problems' (though not directly due to the regexps) :)
calvinkrishy