Reputation: 159
I am trying the following command
new_line=My name is Eric Johnson
sed -i '/# My name is Eric/c\'"${new_line}" /tmp/foo"
Bash sees new_line above in the sed command as a file and says no such file. What is the right way to use the variable in the sed command to replace a whole line with a new line.
Upvotes: 0
Views: 1053
Reputation: 189417
Unfortunately, this is one of those corners of sed
which is poorly standardized. Some variants will absolutely require the newline to be escaped with a backslash; others will regard the escaped newline as something which should be removed before processing.
As a general rule of thumb, use single quotes around your sed
scripts in order to prevent the shell from also modifying the arguments even before sed
starts. However, that means the value of $new_line
will not be interpolated. A common workaround is what I call "seesaw quoting"; put the majority of the script in single quotes, but switch to double quotes where you need the shell to interpolate a variable.
sed -i 's/# My name is Eric Johnson/c\'"${new_line}/" file
Notice how "foo"'bar' = "foobar" = 'foobar' = foobar
(even the unquoted token is okay as long as the string doesn't contain any shell metacharacters, though this is usually not recommended practice).
As a further aside,
new_line=My name is Eric Johnson
is not correct for this case; it will assign new_line=My
and then run the command line name is Eric Johnson
with this variable assignment in place. When the command finishes (or, as on my computer, the shell reports name: command not found
the value of new_line
is reverted to its previous state (undefined if it wasn't defined, or back to its previous value).
Upvotes: 1