1

I have a tenuous grasp of Bash scripting and piping, and have encountered a situation where my limited-experience-based expectation conflicts with reality. I want to remove a substring (specifically a suffix) from a Bash variable using sed. The string and substring are both Bash variables.

> foo1=foo.cpp
> foo2=/main/bar/foo.cpp
> foo3=$(echo $foo2 | sed 's/$foo1//')
> echo $foo3
/main/bar/foo.cpp

If I use a hardcoded string in the sed expression in place of $foo1, the expression behaves as desired:

> foo4=$(echo $foo2 | sed 's/foo\.cpp//')
> echo $foo4
/main/bar/

Can anyone point out what I'm missing to make the foo3 evaluation work such that "foo.cpp" is deleted? Thank you.

StoneThrow
  • 5,314
  • 4
  • 44
  • 86
  • I have tried double-quoting foo1, foo2, and both in the foo3 expression; it does not change the resulting value of foo3. – StoneThrow Mar 17 '16 at 18:53
  • 1
    Screw sed: `echo ${foo2%%$foo1}` – bishop Mar 17 '16 at 18:58
  • Thank you @sat. I'll add this to my bag of tricks for Bash string manipulations. – StoneThrow Mar 17 '16 at 19:07
  • Thank you @bishop. Screwing sed is also a workable solution for me. :) Owing to my tenuous grasp of unix-shell string manipulations, I'm often unclear when strings need to be piped to secondary programs versus when they can be "natively" manipulated by the shell. – StoneThrow Mar 17 '16 at 19:07

1 Answers1

3

With GNU bash 4 and its Parameter Expansion:

foo1="foo.cpp"
foo2="/main/bar/foo.cpp"
foo3="${foo2%$foo1}"
echo "$foo3"

Output:

/main/bar/
Cyrus
  • 84,225
  • 14
  • 89
  • 153