Subham Tripathi
Subham Tripathi

Reputation: 2733

SED not working [unterminated `s' command]

i am trying to replace content of file using sed by following commands

searchString='(<property *name="sourceUrl" *value="\)[^?]*~'
replacementString="file:///tmp/abc-efg"
sed -i 's~\${searchString}\1${replacementString}~g' $file

but it is giving

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

Upvotes: 1

Views: 238

Answers (3)

tripleee
tripleee

Reputation: 189317

I'm guessing you are trying to replace the value="..." parameter and keep the rest?

searchString='\(<property *name="sourceUrl" *value="\)[^"]*'
replacementString="file:///tmp/abc-efg"
sed -i "s~$searchString~\\1$replacementString~" "$file"

I made the following changes:

  • The opening grouping parenthesis requires a backslash (or else the closing parenthesis should also not be backslashed -- this depends on your sed dialect)
  • The regex to match the value="..." field is [^"]* instead of [^?]* -- I don't know whether a question mark makes sense in your particular scenario, but anything which is not a double quote is usually the safe and robust match (within the dark and murky realm of using regex for structured data).
  • Obviously, fix quoting and add the missing ~ delimiter between the search pattern and the replacement string. You had it in the search string (which wasn't being interpolated because of the single quotes) but it's a delimiter, not part of the search string, so it makes more sense to put it in the sed script itself.
  • The search pattern needs to contain one back reference, which is then included in the replacement.
  • The g flag is superfluous, unless you genuinely expect to find multiple matches per input line.

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

your command should be:

sed -i "s~${searchString}~${replacementString}~g" $file
  • ~ missing the internal patterne separator
  • simple -> double quote for variable substitution

but

  • be careful to your 2 string that are treated as regex in sed (so meta character should be escaped or classified

Upvotes: 0

Ewan Mellor
Ewan Mellor

Reputation: 6847

You're missing a separator (which is ~ in your case). It looks like you are trying to put it on the end of $searchString, which is strange. I don't know why you're doing that. The reason it doesn't work is because the variables don't get expanded inside single-quoted strings.

This might work:

sed -i "s~${searchString}\1${replacementString}~g" $file

Really though, it'll be easier to understand like this:

~ $ cat foo
<property name="sourceUrl" value="someurl?param=val"></property>
~ $ searchString='\(<property *name="sourceUrl" *value="\)[^?]*'
~ $ replacementString='file:///tmp/abc-efg'
~ $ sed -e "s~${searchString}~\1${replacementString}~g" foo
<property name="sourceUrl" value="file:///tmp/abc-efg?param=val"></property>

Upvotes: 1

Related Questions