projectz

Tech, Gadgets, Photography, Social Media and Poor Spelling

Question: Is it possible to remove a pathname from a variable in Bash?

I found this on google, a question and answer on removing the path and extention from a bash variable.

Question:


I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION
=`echo "$FILE" | cut -d'.' -f2`

This is bad because it doesn’t work if the filename contains multiple “.” characters. If let’s say I have a.b.js it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path)

but I’d prefer not to fire a Python interpreter just for this, if possible.

Any better ideas?

Answer:

filename=$(basename $fullfile)
extension
=${filename##*.}
filename
=${filename%.*}

Additional Information:

Add some quotes to “$fullfile”, or you’ll risk breaking the filename

Heck, you could even write filename=”${fullfile##*/}” and avoid calling an extra basename
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on May 18, 2011 by in regular and tagged , , , , , .
%d bloggers like this: