2

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?

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

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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