Issue
I am trying to use sed
to find the following line in a text file...
$this->db = new \mysqli("connection");
I have this but it is not working...
sudo sed -i "/$this->db = new \mysqli/c\ \replace with this" /home/me/test.txt
Where am I going wrong, is it the slash in \mysqli
that is stopping it from working?
Solution
In sed
, the backslash is used to escape metacharacters; a single backslash affects how the next character after it is matched, and does not match itself.
Inside single quotes, simply double the backslash to make it match itself. In other words, the first backslash is an escape which means the next backslash is interpreted literally.
Inside double quotes, you may need to add more backslashes still, because the shell also does one round of backslash interpretation before sed
even runs. The shell's backslash removal rules are slightly arcane; it will remove some backslashes, and preserve others. If you don't want to go down that rabbithole, probably simply use single quotes around your script instead.
As an aside, the dollar sign is also a regex metacharacter, so you will need to backslash that as well.
sudo sed -i '/\$this->db = new \\mysqli/c\ \replace with this' /home/me/test.txt
This looks like you are trying to replace a static string in a PHP or Perl program. Often, a much better solution is to make the program itself decide what code to run based on a command-line option or something. In Perl, that might look like
if ($ENV{"poo"} = "bar") { $this->db = something different; }
else { $this->db = new \mysqli("connection"); }
PHP would look even more horrible, but similar in spirit.
Answered By - tripleee Answer Checked By - Terry (WPSolving Volunteer)