Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I am trying to replace a string using the following command:

sed -e "s/\<$5\>/$6/g" "$2/$1" > "$4/$3"

$5-> "hostname=*"
$6-> "hostname=int1"
$2/$1-> "source file path"
$4/$3-> "destination file path" 

When I try to replace the following:

hostname=abc

I get,

hostname=int1=abc

But I want,

hostname=int1

How can I match string to achieve this?

share|improve this question
1  
Please provide part of the source file you want to manage –  Romeo Ninov May 7 at 7:12
    
This looks suspiciously like XML source. Is it? –  Sobrique May 7 at 11:10
    
Yes, this is part of the same script but not related to my question. –  Menon May 7 at 11:20

2 Answers 2

up vote 3 down vote accepted

sed uses regular expressions. These are different from patterns ("globs") that the shell uses.

Notice that the following doesn't work:

$ echo hostname=abc | sed "s/\<hostname=*\>/hostname=int1/"
hostname=int1=abc

But, the following does:

$ echo hostname=abc | sed "s/\<hostname=.*\>/hostname=int1/"
hostname=int1

You need a . before the *.

As a regular expression, hostname=* means hostname followed by zero or more equal signs. Thus sed "s/\<hostname=*\>/hostname=int1/" replaces hostname with hostname=int1.

By contrast, the regular expression hostname=.* means hostname= followed by zero or more any character at all. That is why s/\<hostname=.*\>/hostname=int1/ replaces hostname=abc with hostname=int1.

share|improve this answer
    
Perfect!!! Thanks a lot!!! –  Menon May 7 at 8:23

There might be a better solution than this but you can use the below command.

sed /hostname.*$/s//"hostname=int1"/g /home/path/of/your/original/file > /tmp/hello.$$

cat /tmp/hello.$$ > /home/path/of/your/original/file

Hope it helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.