Ubuntu: unterminated `s' command — running sed from a .sh script, to replace a string that includes a “=”



Question:

I am really struggling with a very silly but complex type of issue while running sed from a .sh script, to replace a string that includes a =.

My command, sed -i 's/^host=.*/host=myhost1/' /opt/file.txt runs very well while I execute from terminal.

However, while I try this command CMD from a .sh file it shows me error like below:

CMD="sed -i 's/^host=.*/host=myhost1/' /opt/file.txt"  

The error I get is:

sed: -e expression #1, char 7: unterminated `s' command  

Looking at the error, I could find it is the problem with = in the search/replace strings. I tried escaping this, and many other options but could not succeed. Even when I remove the = from the strings, it works well from the .sh as well.


Solution:1

When you type CMD="sed -i 's/^host=.*/host=myhost1/' /opt/file.txt", you are using " (double quotes), asking the shell to interpret special characters like *.

It will replace .* with a list of all the files in the current directory that begin with a ., thus confusing sed.

Make the * unspecial with a backslash \*. Also to echo "$CMD" to see the filenames.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »