In my bash
script I have a string and its prefix/suffix. I need to remove the prefix/suffix from the original string.
For example, let's say I have the following values:
string="hello-world" prefix="hell" suffix="ld"
How do I get to the following result?
result="o-wor"
Remove Character from String Using cut Cut is a command-line tool commonly used to extract a portion of text from a string or file and print the result to a standard output. You can also use this command for removing characters from a string.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.
$ 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. […]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With