0

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.

3
  • I think I found an answer to use double quotes so bash knows to expand the variables- sed -i "/# My name is Eric/c \\${new_line}" /tmp/foo. Gonna try and update the answer. Commented Aug 24, 2018 at 1:15
  • It did work but not in this case - ssh {args} remote-host "sed -i "/# My name isEric/c \\${new_line}" /tmp/foo" - sed: -e expression #1, char 2: unterminated address regex. Commented Aug 24, 2018 at 1:32
  • I needed an extra single quotes around the text - sudo sed -i '/# My name is Eric/c \\${new_line}' /tmp/foo" Commented Aug 24, 2018 at 1:58

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

edit - That should have been new_line="My name is Eric Johnson". I apologize.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.