Stripping out extension in file name

This command gives me just the filename without any extension:
evrvar =`echo filename.tar | sed 's/\.[^.]*$//'`

I am trying to make a change to this command... to make it work for... filename.tar.gz to get just the filename....

currently the command gives me filename.tar by removing only gz... I am new to regular expression... pls help.

Thx.

try this:

echo filename.tar.gz |awk -F. '{ print $1 }'

or

echo filename.tar.gz |cut -d'.' -f1

or sed solution

echo "filename.tar.gz" | sed 's/\(.*\)\.\(.*\)\.\(.*\)/\1/g'

or

echo "filename.tar.gz" | sed 's/.......$//g'
1 Like

If filename does not contain period(s):

$ fname="filename.tar.gz"
$ echo "${fname%%.*}"
filename

Otherwise:

${fname%.*.*}

Thanks for the replies.

can this regular expression be made possible to use for both filename.gz & filename.tar.gz

I want to get filename for both of these commands as just filename only:
echo "filename.tar.gz" | sed 's/\(.*\)\.\(.*\)\.\(.\)/\1/g'
echo "filename.gz" | sed 's/\(.*\)\.\(.*\)\.\(.
\)/\1/g'

thanx in advance.

You could use either the awk or the cut solutions they will work in all the scenarios. Here is the sed solution to generalize on both the occasions.

 echo "filename.tar" | sed "s/\([^.*]\)\.\(.*\)*$/\1/g"

echo "filename.tar" | sed "s/\..*$//"

thank you all.. it was helpful

We can even use basename to do this

# will strip out the extension
#+ the result here will be 'new'
basename new.gz '.gz'

How do I strip the extension when the delimiter might occur multiple times in the filename?

For example:
I have 2 files as input for my script.
test.extension
test.foo.extension

In my script I want to see "test" and "test.foo" as results.
But the following script-snippet gives "test" for both files.
I know this is caused by the -f1 that I use as setting for cut. But I want to know which command I should use so it starts looking for the delim-character from the right i.s.o the left (probably a different command than cut, but which?)

!/bin/sh

FILE_NAME=$1
if [ ! -r ${FILE_NAME} ]
then
  echo "Could not find file ${FILE_NAME}"
  exit 1
fi

FNAME=`echo "${FILE_NAME}"| cut -f1 -d'.'`

echo "FNAME = ${FNAME}"

TIA

Nemelis,

Don't hijack another poster's thread, but start your own thread if you have a question!

Thanks.