Thursday, February 3, 2022

[SOLVED] sed not working as expected when trying to replace "user='mysql'" with "user=`whoami`"

Issue

The following command fails.

sed 's/user=\'mysql\'/user=`whoami`/g' input_file

An example input_file contains the following line

user='mysql'

The corresponding expected output is

user=`whoami`

(Yes, I literally want whoami between backticks, I don't want it to expand my userid.)


Solution

This should be what you need:

  • Using double quotes to enclose the sed command,
  • so that you are free to use single quotes in it;
  • escape backticks to avoid the expansion.
sed "s/user='mysql'/user=\`whoami\`/g" yourfile

I've intentionally omitted the -i option for the simple reason that it is not part of the issue.

To clarify the relation between single quotes and escaping, compare the following two commands

  • echo 'I didn\'t know'
  • echo 'I didn'\''t know'

The former will wait for further input as there's an open ', whereas the latter will work fine, as you are concatenating a single quoted string ('I didn'), an escaped single quote (\'), and another single quoted string ('t know').



Answered By - Enlico
Answer Checked By - Katrina (WPSolving Volunteer)