Remove A Prefix Or Suffix From A String In Bash

Posted by Weston Ganger

In a bash script you may need to take a string and remove the prefix/suffix. Heres how to do it.


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

first_word=${string#"$suffix"}
echo $first_word ### Output: hello

second_word=${string%"$prefix"}
echo $second_word ### Output: world

Sorry the solution is so ugly, its just the way it is with bash scripts.


Related External Links:

Article Topic:Software Development - Linux

Date:July 29, 2020