Remove a file extension case-insentively in Bash

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?

ironsand

Posted 2013-08-20T14:19:14.013

Reputation: 1 757

Answers

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.

slhck

Posted 2013-08-20T14:19:14.013

Reputation: 182 472

3

Use parameter expansion

file=/home/johndoe/cv.DOC
basename ${file%.[Dd][Oo][Cc]}

choroba

Posted 2013-08-20T14:19:14.013

Reputation: 14 741

That assumes you know the extension. This wouldn't work for all cases, and especially not with different kinds of files. – slhck – 2013-08-20T14:27:22.137