-2

I tried below command in my script and got error,

sed -i -e 's/\(dataTable\)/$replace \1/' file.txt

Error Message,

sed: -e expression #1, char 22: unknown option to `s'

Please help me in correcting the command to avoid error.

Thanks!

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • 1
    I can't get that error, not on Linux nor on macOS. Character 22 would also be in the middle of the word `replace`, so it doesn't look like it would be taken as an option to `s`, like the `x` in `s/.../.../x` would. You may want to double-check that's the actual command you used. – ilkkachu Aug 25 '21 at 20:55
  • 3
    ... I can imagine it happening if you'd used double quotes rather than single quotes, and `$replace` contains a forward slash character (like `replace=some/thing`) – steeldriver Aug 25 '21 at 22:03

1 Answers1

1

I'm assuming that you are actually using double quotes around your sed expression rather than single quotes, or you would not get that error.

I'm also assuming that you are using a string in your $replace value that contains a slash (/). When the variable is expanded, its value is injected into the sed statement and since it contains a slash, it breaks the syntax for the s/// command.

You can solve this by changing the delimiter that you use in the sed command to some other character that is not present in $replace.

If you choose @, for example,

sed -i -e 's@\(dataTable\)@'"$replace"' \1@' file.txt

Note that you will still have issue is your $replace string contains the substrings \x (where x is any digit), or & (which would be replaced by the part of the string that matches the expression). You will have to escape these special strings.

See e.g.

As a special case, if you plan on replacing a single whole line with new (static) contents, you could do that as follows:

printf '%s\n' "$replace" | sed -e '/some pattern/{ r /dev/stdin' -e 'd; }' file.txt

This finds the line matching /some pattern/ and then reads in the replacement text from standard input (from printf). It then deletes the old line.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936