I am planning to replace certain strings in a file; so I am using sed.
I would like to have the string replaced, while instead, sed read the string and append the text in the middle of the string.
Example:
string in myfile : user=blabla
string that I want to obtain: user=bob
so I run sed in this way, to have it to search for the "user=" string, and replace it with "user=bob"
sed -i 's/user=*/user=bob/' myfile
What I get is
user=bobblabla
Basically sed think that I want to replace just that part, while I want to replace the whole string with the new string. I thought that the * would tell sed to consider anything coming after, but it does not work.
Since I do not know what the "blabla" will be, I can't put it in the sed command. How do I tell sed to find a string that start with "user=" and replace the whole string with the new one?
Best Answer
You seem to be confusing shell patterns with regular expressions. In a shell pattern,
*
means zero or more of any character. In a regular expression, which is whatsed
expects in its patterns,*
means zero or more of the previous atom. In your example, that atom is the=
. So,sed
is searching foruser
followed by zero or more=
and replacing the matching string withuser=bob
. The pattern you want isuser=.*
, which isuser=
followed by any character (.
) zero or more times, making yoursed
command: