5

I learned how to remove prefix and suffix respectively as below:

p="prefix-foo-bar-suffix"
echo ${p#prefix}    # -foo-bar-suffix
echo ${p%suffix}    # prefix-foo-bar-

and I am trying to figure out how to remove them together based on the examples above. I tried the code below but it does not work.

echo ${p#prefix%suffix}    # prefix-foo-bar-suffix, looks like it treats "prefix%suffix" as a whole thing
echo ${{p#prefix}%suffix}    # error, bad substitution

P.S. I know it should be easy to make it work using regex, but here I want to know if it is possible to construct a solution that just builds on top of the # and % tricks. Also, using eval may make it very easy, but as some people suggest, I tend to avoid it here.

Jason Lee
  • 357
  • 2
  • 10

2 Answers2

2

Introduce a helper function:

$ trim() { local x="${1#"$2"}"; echo "${x%"$3"}"; }
$ trim prefix-foo-bar-suffix prefix suffix
-foo-bar-
$ trim prefix-foo-bar-suffix prefix
-foo-bar-suffix
$ trim prefix-foo-bar-suffix "" suffix
prefix-foo-bar-
Leon
  • 31,443
  • 4
  • 72
  • 97
0

Thank you for a good question.

joint use a prefix and suffix is not possible, or do I just could not find it in the documentation.

but if you know the length of a suffix and a prefix that you may fit this simple solution:

echo ${p:6: $[ ${#p}-12 ]}
Dmitriy
  • 386
  • 2
  • 5