6

I want to remove the suffix of a file by using basename in a Bash script. The command removes the suffix only in a case-sensitive way though.

How can I remove a extension case-insensitively?

13

If you want to remove an extension in Bash, you can do this without external tools. Then, pass it to basename:

$ f=/path/to/some/file.foo.bar
$ basename "${f%.*}"
file.foo

With a mixed-case extension:

$ f=/path/to/some/file.foo.Bar
$ basename "${f%.*}"
file.foo

Here, % is string manipulation. It will remove the shortest matching substring from the back of what's in f. The .* matches a dot and zero or more characters, regardless of their case.

3

Use parameter expansion

file=/home/johndoe/cv.DOC
basename ${file%.[Dd][Oo][Cc]}
  • That assumes you know the extension. This wouldn't work for all cases, and especially not with different kinds of files. – slhck Aug 20 '13 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.