Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

marked as duplicate by Gilles, Renan, jasonwryan, Mat, Tim Kennedy Sep 26 '12 at 19:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

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:

FILE=${1##*/}
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.

share|improve this answer
    
Your sed substitution not works for me. For “../folder/file.py” returns “f.py”. –  manatwork Nov 23 '11 at 9:21
    
Sorry, I tested it on a single letter file name. Corrected it –  Kevin Nov 23 '11 at 13:40
add comment

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.

share|improve this answer
1  
That cut has no chance with file names like “M.C. Hammer - U Can't Touch This.txt”. –  manatwork Nov 23 '11 at 9:27
add comment

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