0

I have a script that passes a variable into a sed command like this:

sed "s-\t-&${SUBDIRECTORY}/-"

But if the variable contains - (dash), then the sed command throws an error.

So this script:

VARIABLE="test-variable"
sed "s-\t-&${VARIABLE}/-" 

Results in this error:

sed: 1: "s-\t-&test-variable/-": bad flag in substitute command: 'v'

I have not been able to find any answers to this issue; it works fine without the -.

How can I fix this?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
chriz
  • 1
  • 1

2 Answers2

1

Use a shell parameter expansion that escapes each instance of -:

sed "s-\t-&${VARIABLE//-/\\-}/-"

In the Bash manual, under Shell Parameter Expansion:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. [...]

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

Proper escaping is a fairly difficult problem in the shell, but you could do something like:

$ variable="test-variable"
$ printf '\t\n' | v="$variable" perl -pe 's-\t-$ENV{v}-'
test-variable
William Pursell
  • 204,365
  • 48
  • 270
  • 300