sed: problem while replacing string using wildcard
Solution 1
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
.
Solution 2
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
Related videos on Youtube
Menon
Hi, I am a telecom engineer working in a software based company. Here, I work in billing software which is based on Unix(scripting), SQL and java. Additionally, I have studied web technologies(php,j2ee and asp.net(C#)). I am here to gain knowledge as well as help others whenever I can.
Updated on September 18, 2022Comments
-
Menon over 1 year
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?
-
Atul Vekariya about 9 yearsPlease provide part of the source file you want to manage
-
Sobrique about 9 yearsThis looks suspiciously like XML source. Is it?
-
Menon about 9 yearsYes, this is part of the same script but not related to my question.
-