Possible Duplicate:
Best way to remove file extension from a string?

Say that I have a script called script.sh

In the shell I type

script.sh ../folder/file.py

and in that file I know echo $1 will output ../folder/file.py

But is there anyway of getting just the filename without the extension... file only?


2 Answers 2


BASH has a number of string operators you might want to use here, but I don't see how to do it in just one, so you can either use two statements, or a subshell:

echo `basename ${1%.py}`

Or, more generally,

echo `basename ${1%.*}`

Or, with a temporary variable:

echo ${FILE%.*}

I suppose, as long as you're using a subshell, sed will work too.

echo `echo $1 | sed 's/.*\/\([^/]*\)\(\.[^./]*\)\?/\1/'`

That's a somewhat ugly expression, but it could be cleaned up if you made some assumptions about the input.

  • Your sed substitution not works for me. For “../folder/file.py” returns “f.py”.
    – manatwork
    Nov 23, 2011 at 9:21
  • Sorry, I tested it on a single letter file name. Corrected it
    – Kevin
    Nov 23, 2011 at 13:40

if your extension is always delimited by the point and filenames does not have point(s) inthere, you could use the simple way :

echo $(basename $1) | cut -d. -f1

But definitly the best way is the one described above by Kevin.

  • 1
    That cut has no chance with file names like “M.C. Hammer - U Can't Touch This.txt”.
    – manatwork
    Nov 23, 2011 at 9:27

Not the answer you're looking for? Browse other questions tagged .