Home > front end >  How to escape a character in a variable? [duplicate]
How to escape a character in a variable? [duplicate]

Time:09-17

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?

CodePudding user response:

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. [...]

CodePudding user response:

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
  • Related