How can I remove the extension of a filename in a shell script?

mimicocotopus picture mimicocotopus · Aug 28, 2012 · Viewed 264.3k times · Source

What's wrong with the following code?

name='$filename | cut -f1 -d'.''

As is, I get the literal string $filename | cut -f1 -d'.', but if I remove the quotes I don't get anything. Meanwhile, typing

"test.exe" | cut -f1 -d'.'

in a shell gives me the output I want, test. I already know $filename has been assigned the right value. What I want to do is assign to a variable the filename without the extension.

Answer

chepner picture chepner · Aug 28, 2012

You can also use parameter expansion:

$ filename=foo.txt
$ echo "${filename%.*}"
foo

Just be aware that if there is no file extension, it will look further back for dots, e.g.

  • If the filename only starts with a dot (e.g. .bashrc) it will remove the whole filename.
  • If there's a dot only in the path (e.g. path.to/myfile or ./myfile), then it will trim inside the path.