0

I want to remove the file name extension from a variable based on the extension pattern. Currently, I am interested only to remove two extensions - exe and .cat. I can achieve this using multiple commands. But, wondering if there is a short cut available with a single command.

filename=testfile.exe file=${testfile%.exe}

This will give me the output as "testfile" but if my filename now is: filename=testfile.cat I will have to again run: file=${testfile%.cat}

I want a single command which will give me "testfile" as output.

I don't want to use file=${testfile%.*} as this will remove all the extensions of all other undesired types.

Thanks in Advance!

John Bosco
  • 33
  • 3

1 Answers1

0

Updated to actually answer the question.

You will need to enable the extglob shell option which enables the @(pattern-list). This matches one of the given patterns. In the pattern below the '|' is an or operator and the '$' is a end of string match to avoid

Example Code:

$ shopt -s extglob                   # enables extglob option
$ shopt extglob                      # display current setting
extglob         on
$ filename=testfile.cat.exe
$ file=${filename/@(.cat$|.exe$)/}
$ echo $file
testfile.cat
$ filename=testfile.cat.exe          # What happens when you don't use $
$ echo ${filename/@(.cat|.exe)/}
testfile.exe
$
WaltDe
  • 1,715
  • 8
  • 17
  • input can be testfile.cat or testfile.exe or testfile.o or testfile.bat. The extension should be removed only when extension is .cat or .exe – John Bosco Aug 15 '19 at 16:43
  • @JohnBosco I skipped right over you last requirement didn't I. I've updated the answer. – WaltDe Aug 15 '19 at 20:25