Search code examples
bashreplacepattern-matchingstring-interpolation

Remove a fixed prefix/suffix from a string in Bash


I want to remove the prefix/suffix from a string. For example, given:

string="hello-world"
prefix="hell"
suffix="ld"

How do I get the following result?

"o-wor"

Solution

  • $ prefix="hell"
    $ suffix="ld"
    $ string="hello-world"
    $ foo=${string#"$prefix"}
    $ foo=${foo%"$suffix"}
    $ echo "${foo}"
    o-wor
    

    This is documented in the Shell Parameter Expansion section of the manual:

    ${parameter#word}
    ${parameter##word}

    The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]

    ${parameter%word}
    ${parameter%%word}

    The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]