2

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.

Karthik
  • 145
  • 3
  • 15
  • 3
    Does this answer your question? [Remove a fixed prefix/suffix from a string in Bash](https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash) – tavnab Dec 26 '20 at 22:35
  • Since the question asks about a Unix shell script, duping against a Bash question doesn't seem right. Bash-specific answers, marked as such, seem appropriate here, but POSIX sh answers, IMO, would more closely answer the question as posed. – chwarr Dec 27 '20 at 01:20

2 Answers2

4

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

Try this:

$ Str=$(echo $Str | sed "s/^${prefix}//")
$ echo $Str
FILENAME.xls

Or using awk:

$ echo $Str | awk -F $prefix '{print $2}'
FILENAME.xls
Lee HoYo
  • 1,217
  • 9
  • 9