0

I remove the last slash of my variable:

v="/my/path/"
echo $v | sed 's/\/$//' # echoes /my/path

Now I want to remove a pattern at the end of my variable. This pattern should be set in another variable:

pattern="/"
v="/my/path/"
echo $v | sed 's/"$pattern"$//'  # echoes /my/path/

It does not work. I tried escaping in case of special character such as "/" :

echo $v | sed 's/\"$pattern"$//'  # echoes /my/path/

None expected result either.

How should I proceed?

kaligne
  • 3,098
  • 9
  • 34
  • 60
  • 1
    try `echo $v | sed "s/\\$pattern$//"` – amdixon Oct 29 '15 at 10:12
  • Use different delimiters for sed like `s:::` instead of `s///` or just escape the `/` when you declare it. Also your gonna want your sed script in double quotes so that it expands the variable, but the `$` for the end of line in single quotes. – 123 Oct 29 '15 at 10:15
  • amdixon Double quoting the expression works. Why the double backslash? – kaligne Oct 29 '15 at 10:15
  • so it doesnt interpret the dollar as the literal dollar character ( this would stop it expanding the pattern ) – amdixon Oct 29 '15 at 10:19
  • 1
    Possible duplicate of [sed scripting - environment variable substitution](http://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution) – NeronLeVelu Oct 29 '15 at 10:28

1 Answers1

4

There is no parameter expansion inside single quotes, but inside double quotes. Use

sed "s,$pattern\$,,"

However, to remove a pattern from the end of a variable, why not use the shell's mechanism? This avoids expensive forking and piping:

$ v="/my/path/"
$ echo ${v%/}
/my/path

Which also works with another variable holding the pattern:

$ pattern="/"
$ echo ${v%$pattern}
/my/path
Jens
  • 69,818
  • 15
  • 125
  • 179
  • Why escaping the `$`? It behaves the same without escaping it. – kaligne Oct 29 '15 at 10:18
  • 3
    @kaligne To make it future proof: the shell implements a number of parameters with funny names, such as `$@`, `$_` and so on. If it ever implements `$,` you suddenly wonder why your script no longer works. Escaping it makes sure the `$` is always a plain dollar sign that anchors to the end-of-line. – Jens Oct 29 '15 at 10:52
  • @kaligne, I tend to be extra cautious with `$` sign, & try to keep only minimal required things outside single quotes. e.g. `sed 's,'"$pattern"'$,,'` It however appears dirty & less readable. – anishsane Oct 29 '15 at 12:17