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
  • 2
  • 13
  • 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

3

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
  • 713,503
  • 59
  • 514
  • 593
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,137
  • 8
  • 9