1

I have the need to replace a single line in multiple files and have been playing around with sed for a solution. I am encountering this error:

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

When trying to run a bash script with the following line contained within:

sed -i.bak "s/some-text-string/some-text-string ${stringVar}/" *.ext

I understand that it's the whitespace that is likely causing this issue but I cannot find a solution anywhere. I need to preserve the whitespace in the replacement. I have looked into appending the string but have not been able to get very far using other functions either.

I am probably approaching the problem incorrectly and feel like I should be using a different function, however I don't have a large net of experience with sed or bash and have hit a brick wall.

If anyone could shed some light on a possible solution it would be greatly appreciated.

  • What is the value of $stringVar when the command is failing? – Kusalananda May 26 at 6:53
  • @Kusalananda $stringVar is set to a character string, specifically 'vpnLoginCreds'. No special characters, no spaces, just that exact text string. The answer provided by choroba has solved this issue, but I am still curious as to why it was not possible with 'sed' when it should be able to deal with the whitespace. – WonderingSoul May 27 at 0:21
1

Spaces or tabs should cause no problems, but newlines can break the sed command. The problem is that shell variables are not real variables you might know from other programming languages, they're more similar to macros.

Switching to a real programming language with real variables solves the problem. For example, to keep the syntax similar, a Perl solution:

r=$stringVar perl -i.bak -pe 's/some-text-string/some-text-string$ENV{r}/' -- *.ext

By prepending the assignment to the command, the variable becomes part of the environment where the command runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.