Karthik Karthik - 4 months ago 9
Bash Question

Unix Shell Script: Remove common prefix from a variable

I have 2 variables one which is holding the prefix and other one the complete string.

For e.g

prefix="TEST_"
Str="TEST_FILENAME.xls"


I want the the Str to be compared against prefix and remove that common characters 'TEST_' and i want the output as FILENAME.xls. Please advise if it can be done with minimal lines of coding. Thanks a lot.

Answer

Using BASH you can do:

prefix="TEST_"
str="TEST_FILENAME.xls"
echo "${str#$prefix}"

FILENAME.xls

If not using BASH you can use sed:

sed "s/^$prefix//" <<< "$str"

FILENAME.xls